React - dangerouslySetInnerHTML

I recently came across dangerouslySetInnerHTML while trying to render content returned by my blog API. The blog uses Quill, a rich text editor which allows users to add their blog content with the format of their choosing, which then results in the data being stored in the backend as HTML with tags such as:

<p>some text</p>, <img>, <h2>some heading</h2>,<p><strong>some text</strong></p>

Consider the issue where you will render the returned data from the API in your React app, containing the HTML tags. Example:

const Post = ({post}) => {
// here post is the API data passed to the component as prop
  return (
    <div>{post.content}</div>
  )
}

export default Post

When the component gets rendered, it is not going to be aware of the HTML tags, therefore the output on the screen will have the HTML tags along with its content. Eg

To get around the issue of HTML tags getting rendered and also making React aware of the tags is where dangerouslySetInnerHTML comes in handy. Building upon the previous example:

import DOMPurify from 'dompurify';

const Post = ({post}) => {
// here post is the API data passed to the component as prop
  return (
    <div dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(post.content)}}/>
  )
}

export default Post

Eg

According to the docs: dangerouslySetInnerHTML: An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted, you risk introducing an XSS vulnerability. Read more about using dangerouslySetInnerHTML

Taking into account the security risks involved: the above code example used DOMPurify to sanitize the HTML content.

Whilst using dangerouslySetInnerHTML could potentially introduce security issues, I'd say if you are certain that the code you fetch is not malicious it's a pretty safe bet. If you trust the API you have little to worry about.

That being said, there are sanitization tools for HTML, which detect potentially malicious bits in HTML code and then output a safe and clean HTML. Here are a few to consider:

Thanks for reading, I hope this helps!

Avatar for Fatima Aminu

Written by Fatima Aminu

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.