Table of Contents

How to inject a HTML string in React with the dangerouslySetInnerHTML attribute?

About

How to add a HTML string (for instance for when you have converted a markdown document in an HTML string).

Example

with a function component in Jsx

function DynamicHTML() {
  
  let html = '<h1>Hello World !</h1>';
  return <div dangerouslySetInnerHTML={ { __html: html}} />;
}
<div id="root"></div>
ReactDOM.render(
  <DynamicHTML/>,
  document.getElementById('root')
);

Syntax

In an html element, you pass to the dangerouslySetInnerHTML attribute an object with the attribute named __html that holds the HTML string

<element dangerouslySetInnerHTML={ { __html: htmlString } }/></element>