React.js: Install innerHTML vs. Dangerous SetInnerHTML

Is there any difference “behind the scenes” from setting the innerHTML element versus setting the dangerouslySetInnerHTML property on the element? Suppose I disinfect things correctly for the sake of simplicity.

Example:

var test = React.createClass({ render: function(){ return ( <div contentEditable='true' dangerouslySetInnerHTML={{ __html: "Hello" }}></div> ); } }); 

against

 var test = React.createClass({ componentDidUpdate: function(prevProp, prevState){ this.refs.test.innerHTML = "Hello"; }, render: function(){ return ( <div contentEditable='true' ref='test'></div> ); } }); 

I am doing something more complex than the above, but the general idea is the same

+128
javascript html reactjs
May 20 '16 at 3:04
source share
2 answers

Yes, there is a difference!

The direct effect of using innerHTML compared to dangerouslySetInnerHTML is identical - the DOM node will be updated with the entered HTML.

However, behind the scenes, when you use dangerouslySetInnerHTML , it lets React know that the HTML inside this component is not what it cares about.

Since React uses the virtual DOM, when it goes to compare diff with the actual DOM, it can directly bypass the check of this node because it knows that the HTML comes from a different source. Thus, productivity gains.

More importantly , if you just use innerHTML , React has no way of knowing that the DOM node has been changed. The next time the render function is called, React will overwrite the content that was manually entered so that, in his opinion, the correct state of this DOM node should be.

Your decision to use componentDidUpdate to always keep content in sync. I believe this will work, but there may be a flash during each render.

+174
May 20 '16 at 6:35
source share
— -

Based on ( dangerouslySetInnerHTML ).

It is a prop that does exactly what you want. However, they call it to convey that it should be used with caution

+1
May 20 '16 at 3:43
source share



All Articles