HAST to JSX Runtime Transformer

2.3.6 · active · verified Sun Apr 19

hast-util-to-jsx-runtime is a utility within the unifiedjs ecosystem that transforms a HAST (Hypertext Abstract Syntax Tree) into a representation suitable for automatic JSX runtimes (React, Preact, Solid, Svelte, Vue, etc.). It acts as a bridge, allowing HTML-like content represented as HAST nodes to be rendered efficiently by various JSX-based frameworks without direct framework-specific code. The package is currently at version 2.3.6 and follows a release cadence driven by feature additions, bug fixes, and type improvements, typically releasing patch and minor versions regularly. Its core value proposition is enabling framework-agnostic rendering of parsed HTML, leveraging the standard automatic JSX runtime API for broad compatibility. This design choice differentiates it by providing a unified approach to content rendering across different JSX environments.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates converting a HAST tree to a React static HTML string, illustrating the use of `toJsxRuntime` with React's automatic JSX runtime functions.

import { h } from 'hastscript';
import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
import { Fragment, jsxs, jsx } from 'react/jsx-runtime';
import { renderToStaticMarkup } from 'react-dom/server';

// Create a simple HAST tree
const tree = h('div', { className: 'container' }, [
  h('h1', 'Hello, world!'),
  h('p', 'This is a paragraph rendered from a HAST tree.'),
  h('button', { onClick: 'alert("Clicked!")' }, 'Click Me')
]);

// Transform the HAST tree into JSX elements using React's automatic runtime
// Note: `onClick` is a string here, for actual interactivity in the browser, 
// you would typically handle event listeners differently or use a client-side hydration.
const jsxResult = toJsxRuntime(tree, { Fragment, jsxs, jsx });

// Render the JSX elements to a static HTML string using React DOM server renderer
const doc = renderToStaticMarkup(jsxResult);

console.log(doc);

// Expected output: 
// <div class="container"><h1>Hello, world!</h1><p>This is a paragraph rendered from a HAST tree.</p><button onclick="alert(&quot;Clicked!&quot;)">Click Me</button></div>

view raw JSON →