-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bb4cd93
commit ef8ef3f
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import React from 'react' | ||
import { renderToString } from 'react-dom/server' | ||
import { createMemoryHistory, match, RouterContext } from 'react-router' | ||
import { syncHistoryWithStore } from 'react-router-redux' | ||
import { Provider } from 'react-redux' | ||
|
||
import configureStore from 'common/redux/store' | ||
import routes from 'common/routes' | ||
import Html from 'server/components/Html' | ||
|
||
const renderFullPage = (component, store) => { | ||
const assets = webpackIsomorphicTools.assets() | ||
// Render the component to a string | ||
const html = renderToString(<Html assets={assets} component={component} store={store} />) | ||
|
||
return `<!doctype html>\n${html}` | ||
} | ||
|
||
const handleRender = (ctx) => { | ||
// clear require() cache if in development mode | ||
// (makes asset hot reloading work) | ||
if (__DEV__) { | ||
webpackIsomorphicTools.refresh() | ||
} | ||
|
||
// Compile an initial state | ||
const initialState = {} | ||
// Create a new Redux store instance | ||
const store = configureStore(initialState) | ||
|
||
const _ctx = ctx | ||
const { url: location } = _ctx | ||
const memoryHistory = createMemoryHistory(_ctx.url) | ||
const history = syncHistoryWithStore(memoryHistory, store) | ||
|
||
match({ history, routes, location }, (error, redirectLocation, renderProps) => { | ||
if (error) { | ||
_ctx.status = 500 | ||
_ctx.body = error.message | ||
} else if (redirectLocation) { | ||
_ctx.status = 302 | ||
_ctx.redirect(`${redirectLocation.pathname}${redirectLocation.search}`) | ||
} else if (renderProps) { | ||
const component = ( | ||
<Provider store={store}> | ||
<RouterContext {...renderProps} /> | ||
</Provider> | ||
) | ||
// Send the rendered page back to the client | ||
_ctx.type = 'html' | ||
_ctx.status = 200 | ||
_ctx.body = renderFullPage(component, store) | ||
} else { | ||
_ctx.status = 404 | ||
_ctx.body = 'Not found' | ||
} | ||
}) | ||
} | ||
|
||
export default handleRender |