Insert HTML with React Variable Statements (JSX)

Kyle Hotchkiss picture Kyle Hotchkiss · May 12, 2014 · Viewed 213.5k times · Source

I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:

var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';

and to insert it into react like so, and have it work?

render: function() {
    return (
        <div className="content">{thisIsMyCopy}</div>
    );
}

and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work.

Answer

Douglas picture Douglas · May 14, 2014

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}