Render JSX to an HTML string, with support for Preact components.
npm install preact-render-to-string

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)_ <<
---
``js
import { render } from 'preact-render-to-string';
import { h } from 'preact';
/* @jsx h /
let vdom =
let html = render(vdom);
console.log(html);
//
$3
`js
import { render } from 'preact-render-to-string';
import { h, Component } from 'preact';
/* @jsx h /// Classical components work
class Fox extends Component {
render({ name }) {
return {name};
}
}
// ... and so do pure functional components:
const Box = ({ type, children }) => (
box box-${type}}>{children}
);let html = render(
);
console.log(html);
//
Finn
`---
$3
`js
import express from 'express';
import { h } from 'preact';
import { render } from 'preact-render-to-string';
/* @jsx h /// silly example component:
const Fox = ({ name }) => (
{name}
This page is all about {name}.
);// 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( );
// send it back wrapped up as an HTML5 document:
res.send(
${html});
});
`$3
Rendering errors can be caught by Preact via
getDerivedStateFromErrors or componentDidCatch. To enable that feature in preact-render-to-string set errorBoundaries = true`js
import { options } from 'preact';// Enable error boundaries in
preact-render-to-string
options.errorBoundaries = true;
`---
$3
`bash
npm install preact preact-render-to-string
``jsx
export default () => {
return Home page
;
};
``jsx
import { Suspense, lazy } from 'preact/compat';// Creation of the lazy component
const HomePage = lazy(() => import('./pages/home'));
const Main = () => {
return (
Loading
}>
);
};
``jsx
import { renderToStringAsync } from 'preact-render-to-string';
import { Main } from './main';const main = async () => {
// Rendering of lazy components
const html = await renderToStringAsync();
console.log(html);
//
Home page
};// Execution & error handling
main().catch((error) => {
console.error(error);
});
``---