0

I'm working on a custom gutenberg block, and in the save method, I have dynamically changing HTML in the form of a string.

element.createElement(
    'div',
    null,
    contentString,
)

The above snippet just outputs the HTML as a string, converting all the symbols to HTML entities (<, >, etc.)

How can I go about writing the actual HTML?

closed as off-topic by Jacob Peattie, Nathan Johnson, fuxia Aug 9 at 15:50

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

5

You can use dangerouslysetinnerhtml, a special HTML attribute in React:

dangerouslySetInnerHTML is React’s replacement for using innerHTML 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 out dangerouslySetInnerHTML 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>;
    
1

I haven’t tested it, but you might want to try:

element.createElement(
    'div',
    null,
    {dangerouslySetInnerHTML: {__html: contentString}},
)
  • 1
    The dangerouslySetInnerHTML is actually a HTML attribute and as such, it belongs in the second parameter which is a list of attributes for the element. Your code as it is now will throw an error.. :) – Sally CJ Aug 6 at 14:43
  • 1
    thanks for the correction. Always a bad idea to post untested code... – Vortac Aug 6 at 14:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.