Search code examples
reactjswordpress-gutenberggutenberg-blocks

Wordpress Gutenberg React – render variable with HTML


I have this code in a custom WordPress Gutenberg block

let whole      = Math.floor(stars_client);    
let fraction   = stars_client - whole;
let stars_data = '';

for (var i = 0; i < whole; i ++) {
    stars_data = stars_data + '<i className="fa fa-star" aria-hidden="true"></i>';
}

if (fraction > 0) {
    stars_data = stars_data + '<i class="fa fa-star-half" aria-hidden="true"></i>';
}

return (
    <div className="testimonial-container type_class_3">
        <div className="testimonial-image" style={{ backgroundImage: `url(${imagelinks})` }}></div>
        <div className="testimonial_title">{ testimonial_title }</div>
        <div className="testimmonials_starts">{ stars_data }</div>
        <div className="testimonial-text">{ testimonial_text }</div> 
        <div className="testimonial-author-line"><span className="testimonial-author">{ client_name }</span>, { title_client }</div>
    </div>
);

In stars_data variable I have a generated HTML code that I want to show. Currently the variable is not rendered as HTML. How can I render/display stars_data as HTML code?

Thanks


Solution

  • Your code is being interpretd as plain text and not as an {__html: ''} object. To be able to interpret the HTML code like you need you have to use dangerouslySetInnerHTML which makes use of __html:

    <div className="testimmonials_starts" dangerouslySetInnerHTML={{__html: stars_data}} />
    

    NOTE:

    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.

    And your final code should look something like this:

    let whole      = Math.floor(stars_client);    
    let fraction   = stars_client - whole;
    let stars_data = '';
    
    for (var i = 0; i < whole; i ++) {
        stars_data = stars_data + '<i className="fa fa-star" aria-hidden="true"></i>';
    }
    
    if (fraction > 0) {
        stars_data = stars_data + '<i class="fa fa-star-half" aria-hidden="true"></i>';
    }
    
    return (
        <div className="testimonial-container type_class_3">
            <div className="testimonial-image" style={{ backgroundImage: `url(${imagelinks})` }}></div>
            <div className="testimonial_title">{ testimonial_title }</div>
            <div className="testimmonials_starts" dangerouslySetInnerHTML={{__html: stars_data}} />
            <div className="testimonial-text">{ testimonial_text }</div> 
            <div className="testimonial-author-line"><span className="testimonial-author">{ client_name }</span>, { title_client }</div>
        </div>
    );