Skip to content

How to render HTML in React

New Course Coming Soon:

Get Really Good at Git

Find out how to render an HTML string in the DOM without escaping, using React

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:


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.

One of them is the react-html-parser library.

See the library on GitHub:

Warning: at the time of writing, it’s not been updated in the last 2 years, so things might break in the future. It worked for me.

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: