html-react-parser example

https://github.com/remarkablemark/html-react-parser

by remarkablemark

HTML

<div id="root"></div>

<!-- HTMLReactParser -->
<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>

React

/**
 * GitHub: https://github.com/remarkablemark/html-react-parser
 * Medium: https://medium.com/@remarkablemark/an-alternative-to-dangerously-set-innerhtml-64a12a7c1f96
 * Blog:   https://remarkablemark.org/blog/2016/10/07/dangerously-set-innerhtml-alternative/
 */

function App() {
  function htmlToReact() {
    const html = `
      <h1 style="font-family: Arial;">
        html-react-parser
      </h1>
    `;
    return HTMLReactParser(html);
  }

  function htmlToReactWithReplace() {
    const html = `
      <p>
        This is a demo of <span id="replace">placeholder</span>
      </p>
    `;

    const replace = (domNode) => {
      if (domNode.attribs && domNode.attribs.id === 'replace') {
        return (
          <code>
            <a
              href="https://github.com/remarkablemark/html-react-parser"
              target="_blank"
            >
              html-react-parser
            </a>
          </code>
        );
      }
    };

    return HTMLReactParser(html, { replace });
  }

  return (
    <React.Fragment>
      {htmlToReact()}
      {htmlToReactWithReplace()}
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
);