Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render html in state string [duplicate]

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?

like image 448
qqibrow Avatar asked Mar 22 '15 00:03

qqibrow


People also ask

How do I render a string in HTML?

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).

Should I use dangerouslySetInnerHTML?

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.

Which component uses the render () method for returning HTML?

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.

Why we should not update state directly?

If you try to update state directly then it won't re-render the component.


1 Answers

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.

like image 86
David Hellsing Avatar answered Sep 25 '22 18:09

David Hellsing