React dangerouslysetinnerhtml Example

Last Updated On Thursday 2nd Jun 2022

dangerouslysetinnerhtml

dangerouslySetInnerHTML is an attribute under DOM elements in React.

According to the official documentation , dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM.

This means that if in React if you have to set HTML programmatically or from an external source, you would have to use dangerouslySetInnerHTML instead of traditional innerHTML in Javascript.

innerHTML versus dangerouslySetInnerHTML is identical — the DOM node will update with the injected HTML.

react dangerouslysetinnerhtml

  • React uses a virtual DOM, when it goes to compare the diff against the actual DOM.
  • 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.
  • So there’s performance gains.
  • 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.
	function createMarkup() {
  return {__html: 'First · Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}
	

You can bind to dom directly

	<div dangerouslySetInnerHTML={{__html: '<p>First · Second</p>'}}></div>