How to render HTML in React

Learn how to use React to render HTML strings in the DOM without escaping

I ran into this problem-I need to add an HTML string in the React application, the string comes from the WYSIWYG editor, but just add{myString}ToJSXHTML is being escaped.. in order to show the HTML tags to the user!

How can I solve it? I basically saw 2 solutions. The first native, the second native requires a library.

The first solution: usedangerouslySetInnerHTML

you can use itdangerouslySetInnerHTMLAttributes on HTML elements to add HTML strings within its content:

<div
  dangerouslySetInnerHTML={{
    __html: props.house.description
  }}></div>

Remember, this is calledDangerouslyFor some reason. In this case, the HTML is not escaped at all, which may causeXSSproblem.

But there are good use cases.

The second solution: use a third-party library

There are many libraries that implement the following functionsdangerouslySetInnerHTMLProvided in a simpler way.

One of them isreact-html-parserlibrary.

See the library on GitHub:https://github.com/wrakky/react-html-parser

Warning: At the time of writing, it has not been updated in the past two years, so it may be interrupted 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 usedangerouslySetInnerHTMLthe way.

This seemingly dangerous name is a built-in reminder. Please note that the HTML tags that I allow users to enter the HTML string are correctly whitelisted.

Download mine for freeResponse Handbook


More response tutorials: