spee.ch/server/helpers/handlePageRender.jsx

59 lines
1.8 KiB
React
Raw Normal View History

2018-02-21 22:42:41 +01:00
import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
2018-02-21 22:42:41 +01:00
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router-dom';
2018-03-31 09:20:27 +02:00
import { Reducers, GAListener, App } from 'spee.ch-components';
2018-03-31 21:23:18 +02:00
/*
^ note: to do this right, maybe
these should be passed in from the implementation (www.spee.ch) itself,
so that there are no conflicts between the SSR here and
2018-03-31 21:23:18 +02:00
the bundle sent to the server?
there might also be issues if this package uses a different version of spee.ch-components than www.spee.ch does?
2018-03-31 21:23:18 +02:00
*/
2018-02-21 22:42:41 +01:00
import renderFullPage from './renderFullPage.js';
2018-02-23 20:00:46 +01:00
import Helmet from 'react-helmet';
const siteConfig = require('siteConfig.js');
module.exports = (req, res) => {
let context = {};
// customize the reducer by passing in intial state configs
const CustomizedReducers = Reducers(siteConfig);
const CustomizedApp = App(siteConfig);
// create a new Redux store instance
const store = createStore(CustomizedReducers);
// render component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<GAListener>
<CustomizedApp />
</GAListener>
</StaticRouter>
</Provider>
);
2018-02-23 20:00:46 +01:00
// get head tags from helmet
const helmet = Helmet.renderStatic();
2018-02-22 02:34:29 +01:00
// check for a redirect
if (context.url) {
// Somewhere a `<Redirect>` was rendered
return res.redirect(301, context.url);
2018-02-22 02:34:29 +01: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 20:00:46 +01:00
res.send(renderFullPage(helmet, html, preloadedState));
console.log('hello from spee.ch handlePageRender.jsx');
};