← coderrocketfuel.com

How to Dangerously Set innerHTML in React

There will be times in React when you will need to set HTML programmatically or from an external source.

dangerouslySetInnerHTML is React's replacement for the use of innerHTML in the browser DOM. It allows you to set HTML directly from React by using dangerouslySetInnerHTML and passing an object with a __html key that holds your HTML.

The name dangerouslySetInnerHTML is purposefully chosen to be frightening because it is risky and may accidentally open your users to cross-site scripting (XSS) attacks. So, you need to make sure your HTML is structured properly and sanitized before inserting it into your page.

After you fully understand the security consequences and properly sanitize any HTML data you want to insert, here is an example of how to use it in your React code:

import React, { Component } from "react"
  render() {
    return (
      <div dangerouslySetInnerHTML={{__html: "<p>Your html code here.<p>"}} />

When you open that page in your browser, you'll see the "Your html code here." paragraph text.

As long as your HTML is well formed (i.e. passes XML validation), it will render inside dangerouslySetInnerHTML.