Server-Side Rendering
Griffel provides first class support for Server-Side Rendering.
Next.jsโ
Base setupโ
For basic instructions to setup Next.js, see Getting Started. Please complete the following steps:
- Get a basic Next.js setup running, rendering a page from the
pages
folder, as guided by the tutorial. - Add the Griffel to dependencies (
@griffel/react
package), check Install page.
A complete demo project is available on CodeSandbox.
Configuring a projectโ
- Create a
_document.js
file under yourpages
folder with the following content:
import { createDOMRenderer, renderToStyleElements } from '@griffel/react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
// ๐ creates a renderer
const renderer = createDOMRenderer();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => <App {...props} renderer={renderer} />,
});
const initialProps = await Document.getInitialProps(ctx);
const styles = renderToStyleElements(renderer);
return {
...initialProps,
// ๐ adding our styles elements to output
styles: [...initialProps.styles, ...styles],
};
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
- Create or modify an
_app.js
file under yourpages
folder with the following content:
import { createDOMRenderer, RendererProvider } from '@griffel/react';
function MyApp({ Component, pageProps, renderer }) {
return (
// ๐ accepts a renderer passed from the <Document /> component or creates a default one
<RendererProvider renderer={renderer || createDOMRenderer()}>
<Component {...pageProps} />
</RendererProvider>
);
}
export default MyApp;
- You should now be able to server render components with Griffel styles on any of your pages:
import { makeStyles } from '@griffel/react';
const useClasses = makeStyles({
button: { fontWeight: 'bold' },
});
export default function Home() {
const classes = useClasses();
return <Button className={classes.button}>Hello world!</Button>;
}