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.
npm install html-react-parserVerified import paths — ran on the pinned version, not inferred.
Demonstrates parsing a complex HTML string into React elements, including basic usage and advanced replacement logic for specific tags.
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.
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.
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.
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.
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.
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.