{"id":11708,"library":"react-from-dom","title":"React From DOM: HTML/XML to React Element Converter","description":"react-from-dom is a utility library designed to convert HTML/XML source code strings or existing DOM nodes into React elements. It serves as a safer, more controlled alternative to React's `dangerouslySetInnerHTML`, allowing developers to parse external content and render it as native React components. The current stable version is 0.7.5. The package maintains a steady release cadence, primarily focusing on dependency updates, minor bug fixes, and continuous integration improvements, as seen in the recent 0.7.x releases. Key differentiators include its ability to accept both string and DOM Node inputs, comprehensive options for parsing (e.g., whitespace control, specific selectors, MIME types), and an extensible 'actions' API to modify or replace nodes during conversion, enabling powerful transformations and sanitization workflows not easily achievable with `dangerouslySetInnerHTML`.","status":"active","version":"0.7.5","language":"javascript","source_language":"en","source_url":"git://github.com/gilbarbara/react-from-dom","tags":["javascript","string","DOM","converter","react","component","dangerouslySetInnerHTML","typescript"],"install":[{"cmd":"npm install react-from-dom","lang":"bash","label":"npm"},{"cmd":"yarn add react-from-dom","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-from-dom","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for rendering React elements; supports React 16.8 through 19.","package":"react","optional":false}],"imports":[{"note":"The primary API is a default export function, `convert`.","wrong":"const convert = require('react-from-dom');","symbol":"default","correct":"import convert from 'react-from-dom';"},{"note":"Type import for configuration options when using TypeScript.","symbol":"Options","correct":"import type { Options } from 'react-from-dom';"},{"note":"Type import for defining custom node transformation actions when using TypeScript.","symbol":"Action","correct":"import type { Action } from 'react-from-dom';"}],"quickstart":{"code":"import React from 'react';\nimport convert from 'react-from-dom';\n\n// Example 1: Converting an HTML string\nconst htmlString = `\n  <div class=\"card\">\n    <h3>Welcome to react-from-dom!</h3>\n    <p>This paragraph has <strong>bold text</strong> and an <a href=\"#\">internal link</a>.</p>\n    <img src=\"https://via.placeholder.com/150\" alt=\"Placeholder Image\" />\n    <p style=\"color: red; font-size: 14px;\">Styled content.</p>\n  </div>\n`;\n\nconst reactElementFromString = convert(htmlString, {\n  actions: [\n    {\n      condition: (node) => node.nodeName.toLowerCase() === 'a',\n      pre: (node) => {\n        if (node instanceof HTMLElement) {\n          node.setAttribute('target', '_blank'); // Add target='_blank' to links\n          node.setAttribute('rel', 'noopener noreferrer');\n        }\n        return node;\n      },\n    },\n  ],\n});\n\n// Example 2: Converting an existing DOM Node\nconst rootDomNode = document.createElement('div');\nrootDomNode.id = 'dynamic-root';\nconst p = document.createElement('p');\np.textContent = 'This content came from a dynamically created DOM node.';\nrootDomNode.appendChild(p);\n\nconst reactElementFromDomNode = convert(rootDomNode);\n\nconst App = () => (\n  <div>\n    <h2>Converted from HTML String:</h2>\n    {reactElementFromString}\n\n    <h2>Converted from DOM Node:</h2>\n    {reactElementFromDomNode}\n\n    <p>Note: The link in the first example will open in a new tab due to an 'action'.</p>\n  </div>\n);\n\nexport default App;\n","lang":"typescript","description":"This quickstart demonstrates converting both HTML strings and existing DOM nodes into React elements, including an example of using the `actions` option to modify parsed nodes (adding `target=\"_blank\"` to links)."},"warnings":[{"fix":"Implement a robust HTML sanitization library (e.g., `dompurify`) on the input string *before* passing it to `react-from-dom`.","message":"When parsing untrusted HTML/XML content, always sanitize the input string to prevent XSS (Cross-Site Scripting) vulnerabilities. While `react-from-dom` provides mechanisms like 'actions' for transformation, it does not inherently sanitize input.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Upgrade to `react-from-dom@0.7.0` or newer to ensure full support for fragments and text nodes. Ensure your `react` peer dependency is within the '16.8 - 19' range.","message":"Prior to version 0.7.0, the library might not have fully supported React Fragments or parsing of pure text nodes, leading to unexpected output or errors for certain HTML structures.","severity":"breaking","affected_versions":"<0.7.0"},{"fix":"Only use `randomKey: true` for static content that does not change order or get re-rendered frequently. For dynamic lists, provide a unique, persistent identifier from your data as the `key` prop within a custom `post` action if possible, or process content before conversion.","message":"Using the `randomKey` option for dynamically generated lists or frequently updated content can lead to performance issues and React reconciliation problems. React relies on stable keys to efficiently update list items.","severity":"gotcha","affected_versions":">=0.6.0"},{"fix":"Be mindful of the return type based on `includeAllNodes` and `nodeOnly` options. If an array is returned, ensure your React component iterates over it (e.g., `{array.map(item => item)}`). If `nodeOnly` is true, process the raw DOM nodes as needed.","message":"When `includeAllNodes` is set to `true` with a string input, `react-from-dom` returns an array of React elements. If `nodeOnly` is also true, it returns a `NodeList`. Incorrectly handling these array/NodeList returns when a single element is expected can lead to rendering issues.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For static content, the default key generation is usually sufficient. For dynamic or complex content, consider providing a stable, unique key via a custom `post` action for the root elements of your parsed content, or set `randomKey: true` only if elements are truly static and order doesn't matter for React's reconciliation.","cause":"When converting HTML with multiple sibling elements, React requires a unique key for each element in an array to optimize reconciliation. `react-from-dom` might not always generate sufficiently unique or stable keys by default, or the `randomKey` option was used inappropriately.","error":"Warning: Each child in a list should have a unique \"key\" prop."},{"fix":"Add a check `if (node.nodeType === Node.ELEMENT_NODE)` or `if (node instanceof HTMLElement)` within your action's `condition` or `pre` function before attempting to access element-specific properties.","cause":"This often occurs within `condition` or `pre` actions when `node` is not an `HTMLElement` or `Element` type as expected, but rather a `Text` node or `Comment` node, which lack methods like `toLowerCase` on `nodeName`.","error":"TypeError: Cannot read properties of undefined (reading 'toLowerCase') or similar errors related to node properties."},{"fix":"Ensure that `nodeOnly` is set to `false` (its default) if you intend to render the output directly in a React component. If `nodeOnly` is true, you must manually process the returned DOM nodes, for example, by appending them to an existing DOM element outside of React's render cycle.","cause":"This typically happens if the `convert` function returns a raw DOM node (when `nodeOnly: true` is used with a string input) or an unexpected non-React object type, and React attempts to render it directly.","error":"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object."}],"ecosystem":"npm"}