Create Element From Dynamic HTML String

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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>;
    

Method 2

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

element.createElement(
    'div',
    null,
    {dangerouslySetInnerHTML: {__html: contentString}},
)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x