React From DOM: HTML/XML to React Element Converter

0.7.5 · active · verified Sun Apr 19

react-from-dom is a utility library designed to convert HTML/XML source code strings or existing DOM nodes into React elements. It serves as a safer, more controlled alternative to React's `dangerouslySetInnerHTML`, allowing developers to parse external content and render it as native React components. The current stable version is 0.7.5. The package maintains a steady release cadence, primarily focusing on dependency updates, minor bug fixes, and continuous integration improvements, as seen in the recent 0.7.x releases. Key differentiators include its ability to accept both string and DOM Node inputs, comprehensive options for parsing (e.g., whitespace control, specific selectors, MIME types), and an extensible 'actions' API to modify or replace nodes during conversion, enabling powerful transformations and sanitization workflows not easily achievable with `dangerouslySetInnerHTML`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates converting both HTML strings and existing DOM nodes into React elements, including an example of using the `actions` option to modify parsed nodes (adding `target="_blank"` to links).

import React from 'react';
import convert from 'react-from-dom';

// Example 1: Converting an HTML string
const htmlString = `
  <div class="card">
    <h3>Welcome to react-from-dom!</h3>
    <p>This paragraph has <strong>bold text</strong> and an <a href="#">internal link</a>.</p>
    <img src="https://via.placeholder.com/150" alt="Placeholder Image" />
    <p style="color: red; font-size: 14px;">Styled content.</p>
  </div>
`;

const reactElementFromString = convert(htmlString, {
  actions: [
    {
      condition: (node) => node.nodeName.toLowerCase() === 'a',
      pre: (node) => {
        if (node instanceof HTMLElement) {
          node.setAttribute('target', '_blank'); // Add target='_blank' to links
          node.setAttribute('rel', 'noopener noreferrer');
        }
        return node;
      },
    },
  ],
});

// Example 2: Converting an existing DOM Node
const rootDomNode = document.createElement('div');
rootDomNode.id = 'dynamic-root';
const p = document.createElement('p');
p.textContent = 'This content came from a dynamically created DOM node.';
rootDomNode.appendChild(p);

const reactElementFromDomNode = convert(rootDomNode);

const App = () => (
  <div>
    <h2>Converted from HTML String:</h2>
    {reactElementFromString}

    <h2>Converted from DOM Node:</h2>
    {reactElementFromDomNode}

    <p>Note: The link in the first example will open in a new tab due to an 'action'.</p>
  </div>
);

export default App;

view raw JSON →