Kyle Hotchkiss Kyle Hotchkiss - 5 months ago 68
HTML Question

Insert HTML with React Variable Statements (JSX)

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

You can use dangerouslySetInnerHTML, e.g.

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