You can use dangerouslysetinnerhtml
, a special HTML attribute in React:
dangerouslySetInnerHTML
is React’s replacement for usinginnerHTML
in the browser DOM. In general, setting HTML from code is risky
because it’s easy to inadvertently expose your users to a cross-site
scripting (XSS)
attack. So, you can set HTML directly from React, but you have to type
outdangerouslySetInnerHTML
and pass an object with a__html
key,
to remind yourself that it’s dangerous.
-
ES5:
wp.element.createElement( 'div', { dangerouslySetInnerHTML: { __html: '<b>HTML</b> here' } } );
-
JSX+ESNext:
const createMarkup = ( html ) => { return { __html: html } }; const my_element = <div dangerouslySetInnerHTML={ createMarkup('<b>HTML</b> here') }></div>;
Or in Gutenberg, you can use wp.element.RawHTML()
which basically does the same thing as the snippets above.
-
ES5:
wp.element.RawHTML( { children: '<b>HTML</b> here' } );
-
JSX+ESNext:
import { RawHTML } from '@wordpress/element'; const my_html="some dynamic <b>HTML</b> here!"; const my_element = <RawHTML>{ my_html }</RawHTML>;