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.