I use setState to update part of the html but I found the new update html is not rendered. Here is the code, js fiddle:
html:
<div>hello<br />world<br /></div>
<div id='content'></div>
js:
var Main = React.createClass({
getInitialState: function() {
return {output: 'hello<br />world<br />'};
},
render: function() {
return (
<div>
{this.state.output}
</div>
);
}
});
React.renderComponent(<Main/>, document.getElementById('content'));
I omit the part that update html from the server but the result is the same. How to let the string in state be rendered?
To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).
As the name of the property suggests, it can be dangerous to use because it makes your code vulnerable to cross-site scripting (XSS) attacks. This becomes an issue especially if you are fetching data from a third-party source or rendering content submitted by users.
React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.
If you try to update state directly then it won't re-render the component.
Use dangerouslySetInnerHTML
to inject HTML as a string in React (but note that React won’t be able to use this markup in its virtual DOM):
<div dangerouslySetInnerHTML={{__html: this.state.output}} />
http://jsfiddle.net/5Y8r4/11/
The API for doing this is deliberately complex because this isn't safe to do routinely. React has protections against XSS, using dangerouslySetInnerHTML
circumvents those and opens you up to risk if you aren't sanitizing that data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With