How to render HTML in React
By Flavio Copes
Learn how to render an HTML string in React without it being escaped, using the built-in dangerouslySetInnerHTML attribute or the html-react-parser library.
I had this problem - I needed to add an HTML string in a React application, coming from a WYSIWYG editor, but simply adding {myString} to the JSX was escaping the HTML.. so the HTML tags were displayed to the user!
How did I solve it? I saw 2 solutions, basically. The first native, the second required a library.
First solution: use dangerouslySetInnerHTML
You can use the dangerouslySetInnerHTML attribute on an HTML element to add an HTML string inside its content:
<div
dangerouslySetInnerHTML={{
__html: props.house.description
}}></div>
Remember that it’s called dangerously for a reason. HTML is not escaped at all in this case, and it might cause XSS issues.
But there are good use cases for this.
Second solution: use a 3rd party library
There are many libraries that implement the functionality that dangerouslySetInnerHTML provides, in a simpler way.
When I first wrote this I tried react-html-parser, and it worked for me. That package stopped getting updates in 2022, so today I’d point you to html-react-parser, which is maintained and supports React 19:
npm install html-react-parser
import parse from 'html-react-parser'
export default function HouseDescription({ html }) {
return <div>{parse(html)}</div>
}
parse() turns the HTML string into React elements, so you don’t touch dangerouslySetInnerHTML yourself. It does not sanitize the string though, so if the HTML comes from users you still need to clean it first.
Which one to use?
You can look for other similar libraries, but in the end I chose to use the dangerouslySetInnerHTML way.
This dangerously-looking name was a built-in reminder to pay attention at correctly whitelisting the HTML tags I allowed the user to enter to that HTML string.
A library like DOMPurify does that whitelisting for you: run the string through DOMPurify.sanitize(html) before you pass it to __html or to parse().
Want me to talk about your product? You can sponsor this site.