How to Render HTML in React
Discover the methods to render an HTML string in the DOM without escaping in a React application.
I encountered an issue where I needed to add an HTML string from a WYSIWYG editor into a React application. However, simply adding {myString}
to the JSX implementation resulted in the HTML tags being displayed to the user.
To solve this problem, I found two potential solutions: one utilizing native functionality and the other requiring a third-party library.
First Solution: Using dangerouslySetInnerHTML
To insert an HTML string into the content of an HTML element, you can utilize the dangerouslySetInnerHTML
attribute:
1 | <div dangerouslySetInnerHTML={{ __html: props.house.description }}></div> |
It is important to note that the term “dangerously” is included in the function’s name for a reason. In this case, HTML is not escaped, which opens the possibility for cross-site scripting (XSS) issues. Nonetheless, there are valid use cases for this approach.
Second Solution: Utilizing a 3rd Party Library
Several libraries simplify the implementation of the dangerouslySetInnerHTML
functionality. One such library is react-html-parser
.
Here is the GitHub link for the library: https://github.com/wrakky/react-html-parser
Warning: Please note that, as of the time of writing, this library has not been updated in the past 2 years. While it worked for me, there is a possibility of compatibility issues in the future.
Choosing the Best Approach
Although there are other similar libraries available, I ultimately decided to use the dangerouslySetInnerHTML
method. The name itself serves as a cautionary reminder to accurately whitelist the HTML tags allowed in the user-inputted HTML string.