Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

preact-render-to-string

preactjs7.3mMIT6.5.13TypeScript support: included

Render JSX to an HTML string, with support for Preact components.

preact, render, universal, isomorphic

readme

preact-render-to-string

NPM Build status

Render JSX and Preact components to an HTML string.

Works in Node & the browser, making it useful for universal/isomorphic rendering.

>> Cute Fox-Related Demo (@ CodePen) <<


Render JSX/VDOM to HTML

import { render } from 'preact-render-to-string';
import { h } from 'preact';
/** @jsx h */

let vdom = <div class="foo">content</div>;

let html = render(vdom);
console.log(html);
// <div class="foo">content</div>

Render Preact Components to HTML

import { render } from 'preact-render-to-string';
import { h, Component } from 'preact';
/** @jsx h */

// Classical components work
class Fox extends Component {
    render({ name }) {
        return <span class="fox">{name}</span>;
    }
}

// ... and so do pure functional components:
const Box = ({ type, children }) => (
    <div class={`box box-${type}`}>{children}</div>
);

let html = render(
    <Box type="open">
        <Fox name="Finn" />
    </Box>
);

console.log(html);
// <div class="box box-open"><span class="fox">Finn</span></div>

Render JSX / Preact / Whatever via Express!

import express from 'express';
import { h } from 'preact';
import { render } from 'preact-render-to-string';
/** @jsx h */

// silly example component:
const Fox = ({ name }) => (
    <div class="fox">
        <h5>{name}</h5>
        <p>This page is all about {name}.</p>
    </div>
);

// basic HTTP server via express:
const app = express();
app.listen(8080);

// on each request, render and return a component:
app.get('/:fox', (req, res) => {
    let html = render(<Fox name={req.params.fox} />);
    // send it back wrapped up as an HTML5 document:
    res.send(`<!DOCTYPE html><html><body>${html}</body></html>`);
});

Error Boundaries

Rendering errors can be caught by Preact via getDerivedStateFromErrors or componentDidCatch. To enable that feature in preact-render-to-string set errorBoundaries = true

import { options } from 'preact';

// Enable error boundaries in `preact-render-to-string`
options.errorBoundaries = true;

Suspense & lazy components with preact/compat

npm install preact preact-render-to-string
export default () => {
    return <h1>Home page</h1>;
};
import { Suspense, lazy } from 'preact/compat';

// Creation of the lazy component
const HomePage = lazy(() => import('./pages/home'));

const Main = () => {
    return (
        <Suspense fallback={<p>Loading</p>}>
            <HomePage />
        </Suspense>
    );
};
import { renderToStringAsync } from 'preact-render-to-string';
import { Main } from './main';

const main = async () => {
    // Rendering of lazy components
    const html = await renderToStringAsync(<Main />);

    console.log(html);
    // <h1>Home page</h1>
};

// Execution & error handling
main().catch((error) => {
    console.error(error);
});

License

MIT

changelog

preact-render-to-string

6.5.13

Patch Changes

  • #408 8e8e8ac Thanks @f0x52! - Ensure that the _parent is kept around across multiple suspensions and avoid circular references. In doing so our useId hook should always output unique ids during renderingToString.

  • #409 2afaf31 Thanks @f0x52! - Ensure the renderToStream types of /stream and /stream-node accept a generic for the props of the passed in VNode

  • #405 0a698f6 Thanks @f0x52! - renderToPipeableStream: expose errors through onError, no longer emit un-catchable error event on internal stream

6.5.12

Patch Changes

6.5.11

Patch Changes

6.5.10

Patch Changes

6.5.9

Patch Changes

6.5.8

Patch Changes

6.5.7

Patch Changes

6.5.6

Patch Changes

  • #378 054dae0 Thanks @ccouzens! - Fix issue where preactRenderToString returns a promise of a promise

6.5.5

Patch Changes

  • #372 bebe4bf Thanks @jacob-ebey! - fix: stop client runtime from being corrupted fix: insert ooo chunks in the proper order

6.5.4

Patch Changes

6.5.3

Patch Changes

6.5.2

Patch Changes

6.5.1

Patch Changes

6.5.0

Minor Changes

  • #354 a004914 Thanks @JoviDeCroock! - Introduce a streaming renderer which can be imported from preact-render-to-string/stream and preact-render-to-string/stream-node

Patch Changes

6.4.2

Patch Changes

6.4.1

Patch Changes

6.4.0

Minor Changes

  • #333 6acc97a Thanks @JoviDeCroock! - Allow prepass like behavior where a Promise will be awaited and then continued, this is done with the new renderToStringAsync export

Patch Changes

6.3.1

Patch Changes

6.3.0

Minor Changes

  • 926827c Thanks @marvinhagemeister! - Add support for precompiled JSX transform, see https://deno.com/blog/v1.38#fastest-jsx-transform. Compared to traditional JSX transforms, the precompiled JSX transform tries to pre-serialize as much of the JSX as possible. That way less objects need to be created and serialized which relieves a lot of GC pressure.

    // input
    <div class="foo">hello</div>;
    
    // output
    const tpl = [`<div class="foo">hello</div>`];
    jsxTemplate(tpl);

6.2.2

Patch Changes

6.2.1

Patch Changes

6.2.0

Minor Changes

  • #305 568f139 Thanks @marvinhagemeister! - Add support for error boundaries via componentDidCatch and getDerivedStateFromError

    This feature is disabled by default and can be enabled by toggling the errorBoundaries option:

    import { options } from 'preact';
    
    // Enable error boundaries
    options.errorBoundaries = true;

6.1.0

Minor Changes

  • #301 659b456 Thanks @marvinhagemeister! - Add experimental ability to render HTML comments via <Fragment UNSTABLE_comment="my-comment" />. When the UNSTABLE_comment prop is present all children of that Fragment will be ignored and a HTML comment will be rendered instead. This feature is added to allow framework authors to experiment with marking DOM for hydration in the client. Note that it's marked as unstable and might change in the future.

6.0.3

Patch Changes

6.0.2

Patch Changes

6.0.1

Patch Changes

6.0.0

Major Changes

  • #241 e8cbf66 Thanks @developit! - Improve performance by another 5-10% using switch and short-circuiting, and move pretty-printing from into preact-render-to-string/jsx.

  • #282 6376f62 Thanks @JoviDeCroock! - Remove trailing space for void_elements, this could fail some test_assertions as <img /> will become <img/>, the other VOID_ELEMENTS this will be applied for can be found here

  • #286 7a8b590 Thanks @JoviDeCroock! - Remove the castin to VNode for preact/debug, this is fixed in Preact >= 10.13.0

Patch Changes

5.2.6

Patch Changes

5.2.5

Patch Changes

5.2.4

Patch Changes

5.2.3

Patch Changes

5.2.2

Patch Changes

5.2.1

Patch Changes

5.2.0

Minor Changes

  • #219 250c15f Thanks @developit! - Implement hook state settling. Setting hook state during the execution of a function component (eg: in useMemo) will now re-render the component and use the final result. Previously, these updates were dropped.

5.1.21

Patch Changes

5.1.20

Patch Changes