React HTML Parser

2.0.2 · maintenance · verified Sun Apr 19

react-html-parser is a utility library designed for converting HTML strings into a tree of React components, thereby circumventing the security risks associated with directly using React's `dangerouslySetInnerHTML` property. The library, currently at version 2.0.2, provides a programmatic way to parse HTML content. While its release cadence has been infrequent since its v2.0.0 release in late 2017, it has received recent maintenance updates (v2.0.1 and v2.0.2 in 2020 and 2021 respectively), suggesting it's actively maintained for critical issues rather than undergoing active feature development. A key differentiator is its reliance on `htmlparser2` for robust HTML parsing and its extensive API, which includes `transform` and `preprocessNodes` functions. These functions allow developers fine-grained control over how nodes are processed and rendered, facilitating custom component mapping, attribute manipulation, and node filtering. It also automatically handles the conversion of standard HTML attributes and inline styles to their React equivalents.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to parse an HTML string into React components using `ReactHtmlParser`, including the use of a `transform` function to modify elements (e.g., adding `target="_blank"` to external links) or prevent rendering of specific tags like `script` for security. It showcases handling attributes and passing options.

import React from 'react';
import { ReactHtmlParser } from 'react-html-parser';

function MyHtmlRenderer({ htmlString }) {
  // Example demonstrating parsing an HTML string and applying a custom transform.
  // The transform function can modify or skip nodes based on their properties.
  const transform = (node, index) => {
    // If the node is an <a> tag and has an 'href' attribute,
    // modify it to add 'target="_blank"' for external links.
    if (node.type === 'tag' && node.name === 'a' && node.attribs && node.attribs.href) {
      if (node.attribs.href.startsWith('http') && !node.attribs.href.startsWith(window.location.origin)) {
        node.attribs.target = '_blank';
        node.attribs.rel = 'noopener noreferrer'; // Security best practice
      }
      // Return undefined to let the default parser handle the modified node,
      // or return a custom React element directly.
      return undefined;
    }
    // Return null to prevent rendering specific nodes (e.g., all script tags).
    if (node.type === 'script') {
        return null;
    }
    // For other nodes, let the default parser handle them.
    return undefined;
  };

  const options = {
    decodeEntities: true, // Decode HTML entities like &amp; to & (default since v2.0.0)
    transform: transform,
    // preprocessNodes: (nodes) => { /* modify raw htmlparser2 nodes before processing */ return nodes; }
  };

  return (
    <div className="html-content">
      {ReactHtmlParser(htmlString, options)}
    </div>
  );
}

// Example usage in a parent component
class App extends React.Component {
  render() {
    const exampleHtml = `
      <h1>Welcome!</h1>
      <p>This is some <strong>HTML</strong> content parsed by <code>react-html-parser</code>.</p>
      <img src="https://via.placeholder.com/150" alt="Placeholder image" style="border: 1px solid blue;" />
      <p>Visit our <a href="https://example.com/about">about page</a> or an <a href="https://external.com">external site</a>.</p>
      <script>alert('XSS attempt!');</script>
      `;
    return (
      <div className="app-container">
        <MyHtmlRenderer htmlString={exampleHtml} />
      </div>
    );
  }
}

export default App;

view raw JSON →