10

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?

qqibrow
  • 2,942
  • 1
  • 24
  • 40

1 Answers1

32

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
David Hellsing
  • 106,495
  • 44
  • 176
  • 212