Rendering raw html with reactjs

There are now safer methods to render HTML. I covered this in a previous answer here. You have 4 options, the last uses dangerouslySetInnerHTML.

Methods for rendering HTML

  1. Easiest – Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First ยท Second'}</div>

  2. Safer – Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort – Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Leave a Comment