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 |
|
6 | Render JSX and [Preact] components to an HTML string.
|
7 |
|
8 | Works 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
|
19 | import render from 'preact-render-to-string';
|
20 | import { h } from 'preact';
|
21 | /** @jsx h */
|
22 |
|
23 | let vdom = <div class="foo">content</div>;
|
24 |
|
25 | let html = render(vdom);
|
26 | console.log(html);
|
27 | // <div class="foo">content</div>
|
28 | ```
|
29 |
|
30 |
|
31 | ### Render Preact Components to HTML
|
32 |
|
33 | ```js
|
34 | import render from 'preact-render-to-string';
|
35 | import { h, Component } from 'preact';
|
36 | /** @jsx h */
|
37 |
|
38 | // Classical components work
|
39 | class Fox extends Component {
|
40 | render({ name }) {
|
41 | return <span class="fox">{ name }</span>;
|
42 | }
|
43 | }
|
44 |
|
45 | // ... and so do pure functional components:
|
46 | const Box = ({ type, children }) => (
|
47 | <div class={`box box-${type}`}>{ children }</div>
|
48 | );
|
49 |
|
50 | let html = render(
|
51 | <Box type="open">
|
52 | <Fox name="Finn" />
|
53 | </Box>
|
54 | );
|
55 |
|
56 | console.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
|
67 | import express from 'express';
|
68 | import { h } from 'preact';
|
69 | import render from 'preact-render-to-string';
|
70 | /** @jsx h */
|
71 |
|
72 | // silly example component:
|
73 | const 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:
|
81 | const app = express();
|
82 | app.listen(8080);
|
83 |
|
84 | // on each request, render and return a component:
|
85 | app.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/
|