spee.ch/server/helpers/handlePageRender.jsx

46 lines
1.2 KiB
React
Raw Normal View History

2018-02-21 13:42:41 -08:00
import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
2018-03-21 17:35:51 -07:00
import Reducer from 'client/reducers';
2018-02-21 13:42:41 -08:00
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router-dom';
2018-03-21 17:35:51 -07:00
import GAListener from 'client/components/GAListener/';
import App from 'client/app';
2018-02-21 13:42:41 -08:00
import renderFullPage from './renderFullPage.js';
2018-02-23 11:00:46 -08:00
import Helmet from 'react-helmet';
module.exports = (req, res) => {
let context = {};
// create a new Redux store instance
const store = createStore(Reducer);
// render component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<GAListener>
<App />
</GAListener>
</StaticRouter>
</Provider>
);
2018-02-23 11:00:46 -08:00
// get head tags from helmet
const helmet = Helmet.renderStatic();
2018-02-21 17:34:29 -08:00
// check for a redirect
if (context.url) {
// Somewhere a `<Redirect>` was rendered
return res.redirect(301, context.url);
2018-02-21 17:34:29 -08:00
} else {
// we're good, send the response
}
// get the initial state from our Redux store
const preloadedState = store.getState();
// send the rendered page back to the client
2018-02-23 11:00:46 -08:00
res.send(renderFullPage(helmet, html, preloadedState));
};