To perform server-side rendering, use renderStatic
from glamor, which takes a callback. Render your component inside the callback and all of the calls to css()
will be collected and generated html and css will be returned. This will also return an array of ids to rehydrate the styles for fast startup.
To perform rehydration, call rehydrate
with the array of ids returned by renderStatic
.
Example -
import { renderStatic } from 'glamor/server';
import { rehydrate } from 'glamor';
import { render } from 'react-dom';
import ReactDOMServer from 'react-dom/server';
let { html, css, ids } = renderStatic(() => ReactDOMServer.renderToString(<App />))
return `
<html>
<head>
<style>${css}</style>
</head>
<body>
<div id="app">${html}</div>
<script src="./bundle.js"></script>
<script>
rehydrate(${JSON.stringify(ids)});
render(<App />, document.getElementById('app'));
</script>
</body>
</html>
`
Check out this example on how to use glamorous with Next.js
Glamorous might add duplicate styles to the page due to the intricate nature of es6 imports.
For example -
import App from './App';
rehydrate(${JSON.stringify(ids)}); // ids returned by renderStatic
As import statements get transpiled before other statements, so rehydrate
will be called after regardless of what order you list the statements. This will result in duplicate styles because App
is imported first, so all the styles are added before rehydrate
runs.
To tackle this problem, use a require()
call to order the statements.
rehydrate(${JSON.stringify(ids)});
const App = require('./App');
Or rehydrate
must be run before any other style code if you use any other solution.