score:346

Accepted answer

yes there is a difference!

the immediate effect of using innerhtml versus dangerouslysetinnerhtml is identical -- the dom node will update with the injected html.

however, behind the scenes when you use dangerouslysetinnerhtml it lets react know that the html inside of that component is not something it cares about.

because react uses a virtual dom, when it goes to compare the diff against the actual dom, it can straight up bypass checking the children of that node because it knows the html is coming from another source. so there's performance gains.

more importantly, if you simply use innerhtml, react has no way to know the dom node has been modified. the next time the render function is called, react will overwrite the content that was manually injected with what it thinks the correct state of that dom node should be.

your solution to use componentdidupdate to always ensure the content is in sync i believe would work but there might be a flash during each render.

score:1

yes there is a difference b/w the two: dangerouslysetinnerhtml: react diffing algorithm (https://reactjs.org/docs/reconciliation.html) is designed to ignore the html nodes modified under this attribute thereby slightly improving the performance. if we use innerhtml, react has no way to know the dom is modified. the next time the render  happens, react will overwrite the content that was manually injected with what it thinks the correct state of that dom node should be. that's where componentdidupdate comes to rescue!

score:3

based on (dangerouslysetinnerhtml).

it's a prop that does exactly what you want. however they name it to convey that it should be use with caution

score:19

according to dangerously set innerhtml,

improper use of the innerhtml can open you up to a cross-site scripting (xss) attack. sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. the prop name dangerouslysetinnerhtml is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.

after fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key __html and your sanitized data as the value. here is an example using the jsx syntax:

function createmarkup() {
    return {
       __html: 'first · second'    };
 }; 

<div dangerouslysetinnerhtml={createmarkup()} /> 

read more about it using below link:

documentation: react dom elements - dangerouslysetinnerhtml.

score:26

you can bind to dom directly

<div dangerouslysetinnerhtml={{__html: '<p>first &middot; second</p>'}}></div>

Related Query

More Query from same tag