Adds server side rendering support to react-router-relay using isomorphic-relay.
npm install -S isomorphic-relay isomorphic-relay-router
The instructions are mostly the same as presented here, but with few differences described below.
Load isomorphic-relay-router module:
import IsomorphicRouter from 'isomorphic-relay-router';
When processing a request on the server, get renderProps
using match
function from react-router
(see here),
prepare the data using IsomorphicRouter.prepareData
,
then render React using IsomorphicRouter.RouterContext
in place of RelayRouterContext
,
and send the React output along with the data to the client:
app.get('/*', (req, res, next) => {
match({routes, location: req.originalUrl}, (error, redirectLocation, renderProps) => {
if (error) {
next(error);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
IsomorphicRouter.prepareData(renderProps).then(render, next);
} else {
res.status(404).send('Not Found');
}
function render(data) {
const reactOutput = ReactDOMServer.renderToString(
<IsomorphicRouter.RouterContext {...renderProps} />
);
res.render(path.resolve(__dirname, '..', 'views', 'index.ejs'), {
preloadedData: JSON.stringify(data),
reactOutput
});
}
});
});
Render IsomorphicRouter.Router
instead of IsomorphicRelay.RootContainer
in the browser:
ReactDOM.render(
<IsomorphicRouter.Router routes={routes} history={browserHistory} />,
rootElement
);
See here.