{"id":11720,"library":"react-html-parser","title":"React HTML Parser","description":"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.","status":"maintenance","version":"2.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/wrakky/react-html-parser","tags":["javascript","react","html","htmlparser","htmlparser2","inner html","dangerouslySetInnerHTML"],"install":[{"cmd":"npm install react-html-parser","lang":"bash","label":"npm"},{"cmd":"yarn add react-html-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-html-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for rendering React components; requires ^0.14.0 || ^15.0.0 || ^16.0.0-0.","package":"react","optional":false}],"imports":[{"note":"While it's the primary function, `ReactHtmlParser` is a named export, not the default export.","wrong":"import ReactHtmlParser from 'react-html-parser';","symbol":"ReactHtmlParser","correct":"import { ReactHtmlParser } from 'react-html-parser';"},{"note":"Often used within the `transform` function to re-process modified nodes.","wrong":"const { convertNodeToElement } = require('react-html-parser');","symbol":"convertNodeToElement","correct":"import { convertNodeToElement } from 'react-html-parser';"},{"note":"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.","wrong":"import htmlparser2 from 'htmlparser2';","symbol":"htmlparser2","correct":"import { htmlparser2 } from 'react-html-parser';"}],"quickstart":{"code":"import React from 'react';\nimport { ReactHtmlParser } from 'react-html-parser';\n\nfunction MyHtmlRenderer({ htmlString }) {\n  // Example demonstrating parsing an HTML string and applying a custom transform.\n  // The transform function can modify or skip nodes based on their properties.\n  const transform = (node, index) => {\n    // If the node is an <a> tag and has an 'href' attribute,\n    // modify it to add 'target=\"_blank\"' for external links.\n    if (node.type === 'tag' && node.name === 'a' && node.attribs && node.attribs.href) {\n      if (node.attribs.href.startsWith('http') && !node.attribs.href.startsWith(window.location.origin)) {\n        node.attribs.target = '_blank';\n        node.attribs.rel = 'noopener noreferrer'; // Security best practice\n      }\n      // Return undefined to let the default parser handle the modified node,\n      // or return a custom React element directly.\n      return undefined;\n    }\n    // Return null to prevent rendering specific nodes (e.g., all script tags).\n    if (node.type === 'script') {\n        return null;\n    }\n    // For other nodes, let the default parser handle them.\n    return undefined;\n  };\n\n  const options = {\n    decodeEntities: true, // Decode HTML entities like &amp; to & (default since v2.0.0)\n    transform: transform,\n    // preprocessNodes: (nodes) => { /* modify raw htmlparser2 nodes before processing */ return nodes; }\n  };\n\n  return (\n    <div className=\"html-content\">\n      {ReactHtmlParser(htmlString, options)}\n    </div>\n  );\n}\n\n// Example usage in a parent component\nclass App extends React.Component {\n  render() {\n    const exampleHtml = `\n      <h1>Welcome!</h1>\n      <p>This is some <strong>HTML</strong> content parsed by <code>react-html-parser</code>.</p>\n      <img src=\"https://via.placeholder.com/150\" alt=\"Placeholder image\" style=\"border: 1px solid blue;\" />\n      <p>Visit our <a href=\"https://example.com/about\">about page</a> or an <a href=\"https://external.com\">external site</a>.</p>\n      <script>alert('XSS attempt!');</script>\n      `;\n    return (\n      <div className=\"app-container\">\n        <MyHtmlRenderer htmlString={exampleHtml} />\n      </div>\n    );\n  }\n}\n\nexport default App;","lang":"javascript","description":"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."},"warnings":[{"fix":"Sanitize all untrusted or user-generated HTML input using a robust library such as `DOMPurify` before passing it to `ReactHtmlParser`.","message":"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.","severity":"gotcha","affected_versions":"All"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All"},{"fix":"If the old behavior of preserving HTML entities is desired, set the `decodeEntities` option to `false`: `ReactHtmlParser(html, { decodeEntities: false })`.","message":"Since `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.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Upgrade to `react-html-parser@1.0.2` or a later version to ensure correct rendering of void elements and boolean attributes.","message":"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.","severity":"gotcha","affected_versions":"<1.0.2"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change your import statement from `import ReactHtmlParser from 'react-html-parser';` to `import { ReactHtmlParser } from 'react-html-parser';`.","cause":"The `ReactHtmlParser` function is a named export, but it was imported as a default export.","error":"TypeError: ReactHtmlParser is not a function"},{"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.","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`.","error":"npm ERR! ERESOLVE unable to resolve dependency tree` or `peer dependency: react@^17.0.0"},{"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.","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.","error":"HTML entities (e.g., `&lt;`, `&amp;`) are displayed as plain text instead of their decoded characters (<, &)."}],"ecosystem":"npm"}