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


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


with a function component in Jsx

function DynamicHTML() {
  let html = '<h1>Hello World !</h1>';
  return <div dangerouslySetInnerHTML={ { __html: html}} />;
  • The standard mandatory root DOM node (placeholder for React DOM manipulation)
<div id="root"></div>
  • Rendering of the DynamicHTML component in the root div defined below
  • Output:


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>

Discover More
What are React HTML elements? (Built-In)

In React, HTML elements are: built-in React elements that wraps a HTML element the leaf of the React DOM tree In Jsx A css class that we will apply to our HTML element The component with...

Share this page:
Follow us:
Task Runner