React Render Raw Plain HTML String

Let’s explore all the different ways to render raw HTML strings in React.

dangerouslySetInnerHTML

Using the dangerouslySetInnerHTML property, we can inject an HTML string directly into the DOM.

function Component() {
  const htmlString = '...';
  return <div dangerouslySetInnerHTML={__html: htmlString} />;
}

Refs

Using refs, we could select a DOM element and overwrite its contents by setting its innerHTML property.

import { useRef, useEffect } from 'react';

function Component() {
  const htmlString = '...';
  
  const myRef = useRef();
  useEffect(() => {
    myRef.current.innerHTML = html;
  });

  return (
    <div ref={myRef} />
  );
}

Once you have direct access to the DOM node, there’s a bunch of ways (apart from innerHTML) to inject the HTML string using plain simple JavaScript. I’ve written about all the possible methods in this article.

Direct innerHTML Manipulation

Not the best idea, but sure this is also an approach:

import { useEffect } from 'react';

function Component() {
  const htmlString = '...';

  useEffect(() => {
    document.querySelector('#parent').innerHTML = htmlString;
  });

  return (
    <div id="parent" />
  );
}

Third Party Libraries

Using third party packages like:

Let’s take a look at the first one – html-react-parser:

import parse from 'html-react-parser';

function Component() {
  const htmlString = '...';

  const reactElement = parse(htmlString);

  return reactElement;
}

The parse() method returns a React element which has the benefit of being part of the React Tree while rendering. Hence, the reconciliation and diffing algorithm is able to work properly in this case leading to a more optimised rendering. All the other ways above simply work by setting innerHTML that doesn’t let React optimise re-renders as the changes are entirely flushed every time when the component is updated.

Bonus: None of the solutions or approaches above protects us from XSS vulnerabilities. A decent way to solve for this would be to use a third party library like DOMPurify to sanitize our HTML.

import DOMPurify from 'dompurify';

function Component() {
  const htmlString = DOMPurify.sanitize('...');

  ...
}

Bonus 2: None of the solutions above will execute the script tags present in the HTML string. If you want to solve for that, then head over to this article.

Leave a Reply

Your email address will not be published. Required fields are marked *