React - Dynamic HTML (dangerouslySetInnerHTML attribute)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

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

3 - 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>
Advertising

4 - Example

with a function component

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
ReactDOM.render(
  <DynamicHTML/>,
  document.getElementById('root')
);
  • Output:

web/javascript/react/html_dynamic.txt · Last modified: 2019/06/21 09:23 by gerardnico