-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathrender.js
41 lines (36 loc) · 1.19 KB
/
render.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import escapeStringRegexp from 'escape-string-regexp';
import React from 'react';
import { StaticRouter } from 'react-router-dom';
import { renderToString } from 'react-dom/server';
import { HeadProvider } from 'react-head';
import App from '../../App';
const renderMiddleware = () => (req, res) => {
let html = req.html;
const routerContext = {};
const headTags = []; // mutated during render so you can include in server-rendered template later
const htmlContent = renderToString(
<HeadProvider headTags={headTags}>
<StaticRouter location={req.url} context={routerContext}>
<App />
</StaticRouter>
</HeadProvider>
);
// Here is where we update the server-rendered template
const htmlReplacements = {
HTML_CONTENT: htmlContent, // server-rendered app
REACT_HEAD_CONTENT: renderToString(headTags), // react-head content
};
Object.keys(htmlReplacements).forEach(key => {
const value = htmlReplacements[key];
html = html.replace(
new RegExp('__' + escapeStringRegexp(key) + '__', 'g'),
value
);
});
if (routerContext.url) {
res.redirect(302, routerContext.url);
} else {
res.send(html);
}
};
export default renderMiddleware;