Skip to content

Instantly share code, notes, and snippets.

@ebenoist
Last active October 20, 2016 12:25
Show Gist options
  • Save ebenoist/3564113f46c92d445a43bad1fb26251e to your computer and use it in GitHub Desktop.
Save ebenoist/3564113f46c92d445a43bad1fb26251e to your computer and use it in GitHub Desktop.
A Server Side React Rendering Engine
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const createMemoryHistory = require('history/lib/createMemoryHistory');
const qs = require('qs');
const { RouterContext, match, useRouterHistory } = require('react-router');
const Routes = require('./routes.jsx');
function resolveComponent(name) {
return name
.split('.')
.reduce((obj, index) => obj[index], global);
}
function safeRender(component, props) {
try {
const instance = React.createElement(component, props);
return ReactDOMServer.renderToString(instance);
} catch (e) {
return '';
}
}
function buildHistory() {
// support rails style params
const stringifyQuery = query => qs.stringify(query, { arrayFormat: 'brackets' });
return useRouterHistory(createMemoryHistory)({
parseQueryString: qs.parse,
stringifyQuery,
});
}
function renderRoutedComponent(path) {
let html;
const buildHtml = (_error, _redirectLocation, renderProps) => {
if (!renderProps) {
html = '';
return;
}
html = safeRender(RouterContext, renderProps);
};
match({
routes: resolveComponent(Routes),
location: path,
history: buildHistory(),
}, buildHtml);
return html;
}
function render(name, props = {}, path) {
if (path) {
return renderRoutedComponent(path);
}
const component = resolveComponent(name);
if (!component) { return ''; }
return safeRender(component, props);
}
module.exports = render;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment