{"id":11048,"library":"html-to-react","title":"HTML to React Parser","description":"html-to-react is a lightweight JavaScript library designed to convert raw HTML strings into a React DOM structure. Released last as version 1.7.0 approximately six years ago, it primarily serves applications built with older React versions, evidenced by its peer dependency on `react@^0.13.0 || ^0.14.0 || >=15`. While not actively maintained for recent React releases, it provides a solution for embedding React components within existing HTML templates, specifically addressing scenarios where a page includes HTML generated externally but requires certain sections to be managed by React. This avoids the common issue of creating multiple top-level React roots, instead parsing the entire HTML into a single React element tree. Key features include the ability to define custom processing instructions for specific DOM nodes, allowing for fine-grained control over how HTML elements are transformed into React components.","status":"maintenance","version":"1.7.0","language":"javascript","source_language":"en","source_url":"https://github.com/aknuds1/html-to-react","tags":["javascript","react","react-component","html","typescript"],"install":[{"cmd":"npm install html-to-react","lang":"bash","label":"npm"},{"cmd":"yarn add html-to-react","lang":"bash","label":"yarn"},{"cmd":"pnpm add html-to-react","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for creating and rendering React elements. The library's core functionality relies on React's component model and element creation. The specified peer dependency versions are quite old, indicating potential compatibility issues with modern React.","package":"react","optional":false}],"imports":[{"note":"For ESM environments, use a named import. Older CommonJS examples frequently use `require` to access the `Parser` property of the module's export.","wrong":"const HtmlToReactParser = require('html-to-react').Parser;","symbol":"Parser","correct":"import { Parser } from 'html-to-react';"},{"note":"In ESM, `ProcessNodeDefinitions` is directly available as a named import. In CommonJS, it's typically accessed as a property of the main module export object after requiring the package.","wrong":"const HtmlToReact = require('html-to-react'); const processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions();","symbol":"ProcessNodeDefinitions","correct":"import { ProcessNodeDefinitions } from 'html-to-react';"},{"note":"For TypeScript projects, specific interfaces and types like `HtmlToReactParser`, `ProcessingInstruction`, or `CustomisableNode` can be imported using type-only imports.","symbol":"Type Imports","correct":"import type { HtmlToReactParser, ProcessingInstruction, CustomisableNode } from 'html-to-react';"}],"quickstart":{"code":"import React from 'react';\nimport ReactDOMServer from 'react-dom/server';\nimport { Parser, ProcessNodeDefinitions } from 'html-to-react';\n\ninterface CustomNode extends Node {\n  data?: string;\n  name?: string;\n  parent?: CustomNode; // Add parent for 'shouldProcessNode' logic\n}\n\nconst htmlInput = '<div><h1>Title</h1><p>Paragraph</p><h1>Another title</h1></div>';\nconst htmlExpected = '<div><h1>TITLE</h1><p>Paragraph</p><h1>ANOTHER TITLE</h1></div>';\n\n// A function to determine if a node should be processed\nconst isValidNode = (node: CustomNode) => true;\n\n// Order of instructions matters: most specific to most general\nconst processNodeDefinitions = new ProcessNodeDefinitions();\nconst processingInstructions = [\n  {\n    // Custom processing for <h1> tags: capitalize their content\n    shouldProcessNode: (node: CustomNode) => {\n      // Check if the node is a child of an <h1> tag and contains text data\n      return node.parent && node.parent.name === 'h1' && node.type === 'text';\n    },\n    processNode: (node: CustomNode) => {\n      return node.data?.toUpperCase();\n    }\n  },\n  {\n    // Default processing for all other nodes that haven't been handled\n    shouldProcessNode: (node: CustomNode) => true,\n    processNode: processNodeDefinitions.processDefaultNode\n  }\n];\n\nconst htmlToReactParser = new Parser();\nconst reactComponent = htmlToReactParser.parseWithInstructions(\n  htmlInput,\n  isValidNode,\n  processingInstructions\n);\n\n// Render the resulting React component tree back to static HTML\nconst reactHtml = ReactDOMServer.renderToStaticMarkup(reactComponent);\n\nconsole.log('Original HTML Input:', htmlInput);\nconsole.log('Processed React HTML Output:', reactHtml);\nconsole.log('Assertion (output matches expected):', reactHtml === htmlExpected);\n","lang":"typescript","description":"This example demonstrates how to parse an HTML string, apply custom processing instructions (specifically capitalizing the content of H1 tags), and then render the resulting React component tree back to a static HTML string. It highlights the use of `Parser` and `ProcessNodeDefinitions` with TypeScript typings."},"warnings":[{"fix":"Consider alternative, actively maintained HTML-to-React libraries (e.g., `html-react-parser`, `react-html-parser`) for modern React applications, or fork and adapt the library if its specific functionality is critical and compatibility issues can be resolved.","message":"The library has very old React peer dependencies (`^0.13.0 || ^0.14.0 || >=15`) and has not been updated in over six years. It is highly unlikely to work without issues with modern React versions (e.g., React 17+ or 18+) due to significant changes in React's internal mechanisms, context API, and rendering lifecycle.","severity":"breaking","affected_versions":">=1.0.0 (all versions when used with modern React)"},{"fix":"Carefully arrange processing instructions from most specific to most general. Ensure a broad catch-all instruction (e.g., `shouldProcessNode: () => true`) is placed last if default processing is desired for unhandled nodes.","message":"The order of `processingInstructions` is critical. Instructions are executed sequentially, and the first `shouldProcessNode` that returns `true` for a given node will have its `processNode` method applied. Subsequent instructions for that node will be ignored.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always sanitize HTML input from untrusted sources *before* passing it to `html-to-react`. Use a dedicated HTML sanitization library (e.g., `dompurify`) to strip potentially harmful tags and attributes.","message":"Directly rendering arbitrary user-supplied HTML content can lead to Cross-Site Scripting (XSS) vulnerabilities. While `html-to-react` converts to React elements, it does not inherently sanitize or filter malicious scripts within the HTML input.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Prefer `import { Parser, ProcessNodeDefinitions } from 'html-to-react';` for ESM compatibility. Configure build tools (e.g., Webpack, Rollup) or Node.js environment to handle ESM.","message":"The library's primary examples and age reflect a reliance on CommonJS `require()` syntax. While CommonJS may still function in some environments, modern JavaScript projects typically utilize ESM `import` statements, which are not directly demonstrated in the original documentation.","severity":"deprecated","affected_versions":"<1.7.0 (examples), >=1.7.0 (modern contexts)"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you are using `import { Parser, ProcessNodeDefinitions } from 'html-to-react';` for ESM. Verify the package is installed and accessible in your `node_modules`.","cause":"This error typically occurs when named exports (`Parser`, `ProcessNodeDefinitions`) are not correctly imported from the `html-to-react` module, or when attempting to use CommonJS `require` syntax in an ESM-only environment without proper transpilation.","error":"TypeError: Cannot read properties of undefined (reading 'Parser') or (reading 'ProcessNodeDefinitions')"},{"fix":"Verify that the `react` version installed in your project aligns with the range specified by `html-to-react`'s peer dependencies. For modern React applications, it's strongly recommended to use a different, actively maintained HTML-to-React parsing library.","cause":"This generic React invariant violation often indicates a compatibility issue with the React version being used, rendering invalid React elements, or internal inconsistencies due to the `html-to-react` library's old peer dependencies conflicting with modern React's core mechanisms.","error":"Error: Invariant Violation: Minified React error #XXX; visit https://reactjs.org/docs/error-decoder.html?invariant=XXX for the full message or use the non-minified dev environment for full errors."}],"ecosystem":"npm"}