Member-only story
The Implications of DangerouslySetInnerHTML in React
Hello everyone! In this article, I shall explain what dangerouslySetInnerHTML
is in React and how to use it safely. Let's begin!
The React framework is known to have adopted a browser-independent DOM system, which means it does not interact with the DOM directly. And so in React, you will notice that you are not allowed to add HTML strings directly. For example:
let someHTMLString = "<p>Hello</p>";export default function App() {
return(
<div>{someHTMLString}</div>
);
}
The output would literally be the string <p>Hello</p>
instead of a "Hello" inside a paragraph element.
DangerouslySetInnerHTML
Instead, we can use dangerouslySetInnerHTML
, which is React's version of innerHTML
. It is used as a prop where you can pass an object with a __html
key like so:
dangerouslySetInnerHTML={{__html: getMarkup()}}
The value of the __html
key can be a string which will be injected as HTML code directly from React. This is how React can directly add HTML code to the DOM.
The Dangers of DangerouslySetInnerHTML
As you may have noticed, the name of this prop is particularly frightening for a…