-
-
Notifications
You must be signed in to change notification settings - Fork 632
/
serverRenderReactComponent.js
51 lines (44 loc) · 1.51 KB
/
serverRenderReactComponent.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
42
43
44
45
46
47
48
49
50
51
import ReactDOMServer from 'react-dom/server';
import createReactElement from './createReactElement';
import isRouterResult from './isRouterResult';
import buildConsoleReplay from './buildConsoleReplay';
import handleError from './handleError';
export default function serverRenderReactComponent(options) {
const { name, domNodeId, trace } = options;
let htmlResult = '';
let hasErrors = false;
try {
const reactElementOrRouterResult = createReactElement(options);
if (isRouterResult(reactElementOrRouterResult)) {
// We let the client side handle any redirect
// Set hasErrors in case we want to throw a Rails exception
hasErrors = !!reactElementOrRouterResult.routeError;
if (hasErrors) {
console.error(
`React Router ERROR: ${JSON.stringify(reactElementOrRouterResult.routeError)}`,
);
} else if (trace) {
const redirectLocation = reactElementOrRouterResult.redirectLocation;
const redirectPath = redirectLocation.pathname + redirectLocation.search;
console.log(`\
ROUTER REDIRECT: ${name} to dom node with id: ${domNodeId}, redirect to ${redirectPath}`,
);
}
} else {
htmlResult = ReactDOMServer.renderToString(reactElementOrRouterResult);
}
} catch (e) {
hasErrors = true;
htmlResult = handleError({
e,
name,
serverSide: true,
});
}
const consoleReplayScript = buildConsoleReplay();
return JSON.stringify({
html: htmlResult,
consoleReplayScript,
hasErrors,
});
}