1

I'm using React. I have a string variable in state containing HTML text. This text changes, so I need to be able to insert it into my page and have it appear as rendered HTML, not just a string of text. While I've found some third-party work-arounds, it seems the most direct option is to use the dangerouslySetInnerHTML property. but when I do this, the whole page disappears and my console shows

 // [object Error]
 {}

Here is an example of what I'm trying to do that produces the same results.

const root = ReactDOM.createRoot(document.getElementById("wrapper"));

class Tester extends React.Component {
  constructor(props) {
    super(props);
    this.state = { num: 1, html: "<b>Odd</b>" };
  }
  handleClick() {
    let num = this.state.num + 1;
    let html = "<b>Odd</b>";
    if (num % 2 == 0) {
      html = "<i>Even</i>";
    }
    this.setState({ num: num, html: html });
  }
  render() {
    return (
      <div>
        <h1>Hello {this.state.num}</h1>{" "}
        <button onClick={this.handleClick.bind(this)}>Click</button>
        {/*<div>{this.state.html}</div>*/}
        <div dangerouslySetInnerHTML={{ __HTML: this.state.html }}></div>
      </div>
    );
  }
}

root.render(<Tester />);

I'll note that I am working in CodePen, but that doesn't seem to be the issue. I've found others using this method that work just fine. The link to that CodePen is https://codepen.io/chefdaddyjay/pen/RwyxgeE If you move the comments down a line in the code above, it works, but displays the HTML tags plainly.

1 Answer 1

2

the "html" inside the brackets should be lowercase like this

<div dangerouslySetInnerHTML={{ __html: this.state.html }}></div>

as per the documentation https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml (emphasis mine)

you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.