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`.
npm install react-from-domVerified import paths — ran on the pinned version, not inferred.
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).
Implement a robust HTML sanitization library (e.g., `dompurify`) on the input string *before* passing it to `react-from-dom`.
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.
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.
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.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.
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.
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.