Move client and server apps to a separate file

index.js is the entrypoint file for the bundle and has to render the
app when running within a browser. Separating the app routing init
etc. to a different file allows us to import both ClientApp and
ServerApp in e.g. tests no matter which env we are in.
This commit is contained in:
Kimmo Puputti 2017-01-11 16:01:35 +02:00
parent 82640d4d0c
commit 4e2aedbd14
2 changed files with 40 additions and 37 deletions

38
src/app.js Normal file
View file

@ -0,0 +1,38 @@
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Helmet from 'react-helmet';
import { BrowserRouter, ServerRouter } from 'react-router';
import Routes from './Routes';
export const ClientApp = () => (
<BrowserRouter>
<Routes />
</BrowserRouter>
);
export const ServerApp = (props) => {
const { url, context } = props;
return (
<ServerRouter location={ url } context={ context } >
<Routes />
</ServerRouter>
);
};
/**
* Render the given route.
*
* @param {String} url Path to render
* @param {Object} serverContext Server rendering context from react-router
*
* @returns {Object} Object with keys:
* - {String} body: Rendered application body of the given route
* - {Object} head: Application head metadata from react-helmet
*/
export const renderApp = (url, serverContext) => {
const body = ReactDOMServer.renderToString(
<ServerApp url={ url } context={ serverContext }/>
);
const head = Helmet.rewind();
return { head, body };
};

View file

@ -13,49 +13,14 @@
import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import Helmet from 'react-helmet';
import { BrowserRouter, ServerRouter } from 'react-router';
import Routes from './Routes';
import { ClientApp, renderApp } from './app';
import './index.css';
const ClientApp = () => (
<BrowserRouter>
<Routes />
</BrowserRouter>
);
const ServerApp = (props) => {
const { url, context } = props;
return (
<ServerRouter location={ url } context={ context } >
<Routes />
</ServerRouter>
);
};
// If we're in a browser already, render the client application.
if (typeof window !== 'undefined') {
ReactDOM.render(<ClientApp />, document.getElementById('root'));
}
/**
* Render the given route.
*
* @param {String} url Path to render
* @param {Object} serverContext Server rendering context from react-router
*
* @returns {Object} Object with keys:
* - {String} body: Rendered application body of the given route
* - {Object} head: Application head metadata from react-helmet
*/
const renderApp = (url, serverContext) => {
const body = ReactDOMServer.renderToString(
<ServerApp url={ url } context={ serverContext }/>
);
const head = Helmet.rewind();
return { head, body };
};
// Export the function for server side rendering.
export default renderApp;