Skip to content

Instantly share code, notes, and snippets.

@ejangi
Created June 24, 2021 02:58
Show Gist options
  • Save ejangi/3d785fdf537b13cc20a87e39dc568818 to your computer and use it in GitHub Desktop.
Save ejangi/3d785fdf537b13cc20a87e39dc568818 to your computer and use it in GitHub Desktop.
Next JS server side styles rendering
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';
import theme from '../styles/theme';
// This makes sure that Material UI renders correctly on the server side as well
// See https://dev.to/felixmohr/setting-up-a-blog-with-next-js-react-material-ui-and-typescript-2m6k
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<meta name="theme-color" content={theme.palette.primary.main} />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
MyDocument.getInitialProps = async (ctx) => {
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment