Registry / web-framework / react-html-parser

react-html-parser

JSON →
library2.0.2jsnpmunverified

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.

npm install react-html-parser
INSTALL
IMPORT
SIG · REACT-HTML-PARSER
R
react-html-parser
web-frameworkjavascriptv2.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ReactHtmlParser
import { ReactHtmlParser } from 'react-html-parser';
import ReactHtmlParser from 'react-html-parser';
While it's the primary function, `ReactHtmlParser` is a named export, not the default export.
convertNodeToElement
import { convertNodeToElement } from 'react-html-parser';
const { convertNodeToElement } = require('react-html-parser');
Often used within the `transform` function to re-process modified nodes.
htmlparser2
import { htmlparser2 } from 'react-html-parser';
import htmlparser2 from 'htmlparser2';
The underlying `htmlparser2` library is exposed as a named export from `react-html-parser` for advanced use cases, not as a direct import from its own package.

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;
Debug
Known issues
gotchaWhile `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.
fix
Sanitize all untrusted or user-generated HTML input using a robust library such as `DOMPurify` before passing it to `ReactHtmlParser`.
affects: All
gotchaThe 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.
fix
Ensure your project's React version is within the compatible range. If using npm v7+, `npm install --legacy-peer-deps` might temporarily resolve installation errors but is not recommended for production without careful consideration of potential incompatibilities.
affects: All
breakingSince `v2.0.0`, HTML entities (e.g., `&amp;`) are decoded by default. This changes the behavior from `v1.x` where entities were preserved as-is.
fix
If the old behavior of preserving HTML entities is desired, set the `decodeEntities` option to `false`: `ReactHtmlParser(html, { decodeEntities: false })`.
affects: >=2.0.0
breakingAs 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.
fix
Manually wrap these tags in `div` elements within your HTML string if the previous structure is essential, or adjust your CSS and layout expectations to account for the direct rendering of these tags.
affects: >=2.0.0
gotchaVersions 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.
fix
Upgrade to `react-html-parser@1.0.2` or a later version to ensure correct rendering of void elements and boolean attributes.
affects: <1.0.2
Errors
Common errors & fixes
TypeError: ReactHtmlParser is not a function
The `ReactHtmlParser` function is a named export, but it was imported as a default export.
fix
Change 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
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`.
fix
Adjust 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., `&lt;`, `&amp;`) are displayed as plain text instead of their decoded characters (<, &).
The `decodeEntities` option is explicitly set to `false`, or you are using `v1.x` of the library where entity decoding was off by default.
fix
Ensure 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.
Upgrade
Version history
2.0.2latest on npm
Audit
Dependencies
reactrequiredPeer dependency for rendering React components; requires ^0.14.0 || ^15.0.0 || ^16.0.0-0.
Agent activity
4 hits · last 30 days
node
4
Resources
react-html-parser — npm install react-html-parser · libregistry