React HTML Parser
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
-
TypeError: ReactHtmlParser is not a function
cause The `ReactHtmlParser` function is a named export, but it was imported as a default export.fixChange your import statement from `import ReactHtmlParser from 'react-html-parser';` to `import { ReactHtmlParser } from 'react-html-parser';`. -
npm ERR! ERESOLVE unable to resolve dependency tree` or `peer dependency: react@^17.0.0
cause Your project's installed `react` version (e.g., React 17 or 18) falls outside the peer dependency range (`^0.14.0 || ^15.0.0 || ^16.0.0-0`) required by `react-html-parser`.fixAdjust your project's `react` version to be compatible (e.g., `react@16`). If absolutely necessary and aware of potential incompatibilities, you might use `npm install --legacy-peer-deps` (for npm v7+) but this is not a recommended long-term solution. -
HTML entities (e.g., `<`, `&`) are displayed as plain text instead of their decoded characters (<, &).
cause The `decodeEntities` option is explicitly set to `false`, or you are using `v1.x` of the library where entity decoding was off by default.fixEnsure the `decodeEntities` option is set to `true` (which is the default behavior since `v2.0.0`), or upgrade to `v2.0.0` or higher to benefit from default entity decoding. For `v1.x`, you would need to manually decode entities before passing the HTML string.
Warnings
- gotcha While `react-html-parser` avoids `dangerouslySetInnerHTML`, parsing arbitrary, untrusted HTML without prior sanitization can still introduce Cross-Site Scripting (XSS) vulnerabilities. The `transform` function can provide some control, but a dedicated HTML sanitizer (like DOMPurify) is strongly recommended for user-generated or untrusted content.
- gotcha The package has a peer dependency on React versions `^0.14.0 || ^15.0.0 || ^16.0.0-0`. Using an incompatible React version (e.g., React 17 or 18) will lead to installation errors or potential runtime issues.
- breaking Since `v2.0.0`, HTML entities (e.g., `&`) are decoded by default. This changes the behavior from `v1.x` where entities were preserved as-is.
- breaking As of `v2.0.0`, `<html>`, `<head>`, and `<body>` tags are no longer automatically converted to `<div>` elements. This change might impact styling or DOM structure if your application was relying on the previous automatic wrapping behavior.
- gotcha Versions prior to `v1.0.2` contained known bugs related to incorrectly rendering void elements (like `<img>`, `<br>`) and boolean attributes (e.g., `disabled`, `checked`). Using these older versions can lead to malformed HTML output.
Install
-
npm install react-html-parser -
yarn add react-html-parser -
pnpm add react-html-parser
Imports
- ReactHtmlParser
import ReactHtmlParser from 'react-html-parser';
import { ReactHtmlParser } from 'react-html-parser'; - convertNodeToElement
const { convertNodeToElement } = require('react-html-parser');import { convertNodeToElement } from 'react-html-parser'; - htmlparser2
import htmlparser2 from 'htmlparser2';
import { htmlparser2 } from 'react-html-parser';
Quickstart
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 & 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;