UNPKG

2.14 kBMarkdownView Raw
1# preact-render-to-string
2
3[![NPM](http://img.shields.io/npm/v/preact-render-to-string.svg)](https://www.npmjs.com/package/preact-render-to-string)
4[![travis-ci](https://travis-ci.org/developit/preact-render-to-string.svg)](https://travis-ci.org/developit/preact-render-to-string)
5
6Render JSX and [Preact] components to an HTML string.
7
8Works in Node & the browser, making it useful for universal/isomorphic rendering.
9
10\>\> **[Cute Fox-Related Demo](http://codepen.io/developit/pen/dYZqjE?editors=001)** _(@ CodePen)_ <<
11
12
13---
14
15
16### Render JSX/VDOM to HTML
17
18```js
19import render from 'preact-render-to-string';
20import { h } from 'preact';
21/** @jsx h */
22
23let vdom = <div class="foo">content</div>;
24
25let html = render(vdom);
26console.log(html);
27// <div class="foo">content</div>
28```
29
30
31### Render Preact Components to HTML
32
33```js
34import render from 'preact-render-to-string';
35import { h, Component } from 'preact';
36/** @jsx h */
37
38// Classical components work
39class Fox extends Component {
40 render({ name }) {
41 return <span class="fox">{ name }</span>;
42 }
43}
44
45// ... and so do pure functional components:
46const Box = ({ type, children }) => (
47 <div class={`box box-${type}`}>{ children }</div>
48);
49
50let html = render(
51 <Box type="open">
52 <Fox name="Finn" />
53 </Box>
54);
55
56console.log(html);
57// <div class="box box-open"><span class="fox">Finn</span></div>
58```
59
60
61---
62
63
64### Render JSX / Preact / Whatever via Express!
65
66```js
67import express from 'express';
68import { h } from 'preact';
69import render from 'preact-render-to-string';
70/** @jsx h */
71
72// silly example component:
73const Fox = ({ name }) => (
74 <div class="fox">
75 <h5>{ name }</h5>
76 <p>This page is all about {name}.</p>
77 </div>
78);
79
80// basic HTTP server via express:
81const app = express();
82app.listen(8080);
83
84// on each request, render and return a component:
85app.get('/:fox', (req, res) => {
86 let html = render(<Fox name={req.params.fox} />);
87 // send it back wrapped up as an HTML5 document:
88 res.send(`<!DOCTYPE html><html><body>${html}</body></html>`);
89});
90```
91
92
93---
94
95
96### License
97
98[MIT]
99
100
101[Preact]: https://github.com/developit/preact
102[MIT]: http://choosealicense.com/licenses/mit/