Last active
April 13, 2017 01:43
-
-
Save jschr/93fb4d5b448d3390ede2e055eba940e8 to your computer and use it in GitHub Desktop.
glamor ssr
This file contains hidden or 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
import * as React from 'react' | |
import { renderToString, renderToStaticMarkup } from 'react-dom/server' | |
import { renderStatic } from 'glamor/server' | |
import Template from './components/Template' | |
export default function ssr({ webpackStats, appProps }) { | |
const assets = Object.keys(webpackStats.compilation.assets) | |
const js = assets.filter(value => value.match(/\.js$/)) | |
// use require to ensure glamor rehydrate is called | |
// before styles are created | |
const App = require('./components/App').default | |
// get the initial css stylesheet and glamor | |
// server state (cssIds) | |
const { html: body, css, ids: cssIds } = renderStatic(() => { | |
return renderToString(<App {...appProps} />) | |
}) | |
const templateProps = { | |
css, | |
js, | |
body, | |
ssr: { | |
// pass glamor state to rehydrate from the browser | |
cssIds, | |
appProps | |
} | |
} | |
const html = ` | |
<!doctype html> | |
${renderToStaticMarkup(<Template {...templateProps} />)} | |
` | |
return html | |
} |
This file contains hidden or 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
import * as React from 'react' | |
export default function Template({ css, js, body, ssr }) { | |
return ( | |
<html lang='en' data-timestamp={(new Date()).toISOString()}> | |
<head> | |
<title>{ssr.appProps.username}</title> | |
<style>{css}</style> | |
</head> | |
<body> | |
<div id='react-root' dangerouslySetInnerHTML={{ __html: props.body }} /> | |
<script dangerouslySetInnerHTML={{ __html: `window.ssr = ${JSON.stringify(props.ssr)}` }} /> | |
</body> | |
</html> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment