{"id":13302,"library":"html-react-parser","title":"HTML to React Parser","description":"html-react-parser is a utility library designed to convert HTML strings into React elements, making it suitable for rendering dynamic content securely and efficiently within React applications. The current stable version is 6.0.1. The package maintains a fairly active release cadence, with frequent patch updates addressing dependency bumps and minor fixes, alongside major versions introducing breaking changes, typically related to underlying parser updates or build configurations. A key differentiator is its ability to operate seamlessly in both Node.js (server-side rendering) and browser environments. It provides powerful customization options like the `replace` and `transform` functions, allowing developers fine-grained control over how HTML nodes are converted and rendered, including advanced use cases like sanitization or replacing specific elements with custom React components. It ships with TypeScript types for improved developer experience.","status":"active","version":"6.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/remarkablemark/html-react-parser","tags":["javascript","html-react-parser","html","react","parser","dom","typescript"],"install":[{"cmd":"npm install html-react-parser","lang":"bash","label":"npm"},{"cmd":"yarn add html-react-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add html-react-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"TypeScript types for React, required when using TypeScript in projects targeting various React versions.","package":"@types/react","optional":true},{"reason":"Core dependency for creating and rendering React elements.","package":"react","optional":false}],"imports":[{"note":"The primary function is a default export. For CommonJS, use `require('html-react-parser')` directly.","wrong":"const parse = require('html-react-parser');","symbol":"parse","correct":"import parse from 'html-react-parser';"},{"note":"Import the type definition for the parser options when working with TypeScript to ensure type safety for the `options` object.","symbol":"HTMLReactParserOptions","correct":"import type { HTMLReactParserOptions } from 'html-react-parser';"},{"note":"Import specific DOM node types like `Element` if you are implementing custom `replace` or `transform` functions with TypeScript and need to assert node types.","symbol":"Element","correct":"import type { Element } from 'html-react-parser';"}],"quickstart":{"code":"import parse from 'html-react-parser';\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nconst htmlString = `\n  <div>\n    <h1>Welcome to My Blog!</h1>\n    <p>This is a paragraph with <strong>bold text</strong> and an <a href=\"#\">example link</a>.</p>\n    <ul>\n      <li>Item 1</li>\n      <li>Item 2</li>\n    </ul>\n    <img src=\"https://via.placeholder.com/150\" alt=\"Placeholder Image\" />\n    <p style=\"color: blue;\">This text is blue.</p>\n  </div>\n`;\n\nconst App = () => (\n  <div>\n    <h2>Parsed HTML Content:</h2>\n    {parse(htmlString, {\n      replace: (node) => {\n        // Example: Replace 'a' tags with custom component or modify props\n        if (node.type === 'tag' && node.name === 'a') {\n          return (\n            <a {...node.attribs} style={{ color: 'red' }}>\n              {node.children ? parse(node.children.map(child => child.data || child.children?.map(c => c.data).join('') || '').join('')) : ''}\n            </a>\n          );\n        }\n        // Example: Remove 'img' tags\n        if (node.type === 'tag' && node.name === 'img') {\n          return <p>Image removed for security reasons.</p>;\n        }\n        return node; // Return the node to be parsed normally if no replacement is needed\n      },\n    })}\n  </div>\n);\n\nconst root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);\nroot.render(<App />);","lang":"typescript","description":"Demonstrates parsing a complex HTML string into React elements, including basic usage and advanced replacement logic for specific tags."},"warnings":[{"fix":"Review your HTML input and custom `replace` or `transform` functions, especially if you rely on specific behaviors of older `html-dom-parser` or `domhandler` versions. Test thoroughly after upgrading.","message":"Version 6.0.0 introduced breaking changes by bumping the underlying `html-dom-parser` from 5.1.8 to 7.0.0 and `domhandler` from 5.0.3 to 6.0.1. These dependency updates may alter how certain malformed HTML is parsed or how DOM nodes are structured internally.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Ensure your project's build tooling (e.g., Babel, Webpack) is configured to transpile `es2016` syntax down to your desired target environment (e.g., `es5` for older browsers) if necessary.","message":"The build target for html-react-parser changed from `es5` to `es2016` in version 6.0.0. This means the distributed code will target a more modern JavaScript environment.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Always sanitize untrusted HTML before passing it to `html-react-parser` using a dedicated sanitization library (e.g., `dompurify`). Alternatively, implement a robust `replace` function to explicitly filter out dangerous tags and attributes.","message":"This library is not XSS-safe by default. If you parse untrusted HTML, malicious scripts or attributes could be injected into your React tree, leading to XSS vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For untrusted HTML, explicitly remove all `<script>` tags using the `replace` option or a sanitization library before parsing to prevent any potential execution or manipulation of the DOM.","message":"By default, `<script>` tags are parsed but not executed by React. However, if they contain certain attributes or are part of custom replacement logic, they might still pose a security risk.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"You must narrow the type of `node` to `Element` before accessing `node.attribs`. Use a type guard like `if (node.type === 'tag')` to ensure `node` is an HTML element.","cause":"In TypeScript, the `DOMNode` type returned in the `replace` or `transform` functions is a union type that includes various node types (text, comment, element). The `attribs` property only exists on `Element` nodes.","error":"TS Error: Property 'attribs' does not exist on type 'DOMNode'"},{"fix":"Ensure your HTML is well-formed. For event handlers, you often need to use React's camelCase synthetic events (e.g., `onClick` instead of `onclick`) and pass a function reference. For complex interactions, use the `replace` option to convert problematic HTML elements into proper React components with their own event handlers.","cause":"React handles DOM events differently than plain HTML. It uses a synthetic event system, and some HTML attributes (like `onclick`) are not directly mapped to React props or are case-sensitive (e.g., `onClick` in React). Incorrect HTML structure can also lead to parsing issues.","error":"Elements aren't nested correctly or attributes aren't getting called (e.g., `onclick` not firing)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}