rehype-react

8.0.0 · active · verified Sun Apr 19

rehype-react is a `rehype` plugin designed to compile HTML abstract syntax trees (hast) into JSX elements, enabling the rendering of HTML content within various JSX runtimes. It currently supports React, Preact, Solid, Svelte, and Vue. The current stable version is 8.0.0. The project maintains an active release cadence with frequent patch and minor updates, and major versions are released to introduce significant architectural changes, such as the move to ESM or multi-framework support. A key differentiator is its integration within the `unified` ecosystem, allowing developers to leverage a rich pipeline of AST transformations on HTML content before it's rendered. This provides more control compared to simpler solutions like `react-markdown` and offers an alternative to `react-remark` for HTML processing.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `rehype-react` within a React component to transform an HTML string into a React element tree, supporting multiple JSX runtimes since v8.0.0.

import { Fragment, createElement, useEffect, useState } from 'react';
import * as prod from 'react/jsx-runtime';
import rehypeParse from 'rehype-parse';
import rehypeReact from 'rehype-react';
import { unified } from 'unified';

// To run this example:
// npm install react react-dom rehype-parse rehype-react unified

// @ts-expect-error: The react types might be missing for `prod` object
const production = { Fragment: prod.Fragment, jsx: prod.jsx, jsxs: prod.jsxs };

const htmlContent = `<h2>Hello, world from rehype-react!</h2>\n<p>This paragraph contains <em>emphasized</em> text and a <a href="#">link</a>.</p>\n<p>Current Node.js version is ${process.version}.</p>`;

/**
 * A React hook to process HTML content using rehype-react.
 * @param {string} text The HTML string to process.
 * @returns {JSX.Element} A React component tree.
 */
function useHtmlProcessor(text) {
  const [Content, setContent] = useState(createElement(Fragment));

  useEffect(
    function () {
      (async function () {
        const file = await unified()
          .use(rehypeParse, { fragment: true })
          .use(rehypeReact, production)
          .process(text);

        setContent(file.result);
      })();
    },
    [text]
  );

  return Content;
}

export default function App() {
  return useHtmlProcessor(htmlContent);
}

// In a typical React app, you would render <App /> using ReactDOM.createRoot:
// import ReactDOM from 'react-dom/client';
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(<App />);

view raw JSON →