Skip to content

Instantly share code, notes, and snippets.

@AugustoCalaca
Created July 21, 2020 17:41
Show Gist options
  • Save AugustoCalaca/fa35600d3b2e63ecac4709aa6658c963 to your computer and use it in GitHub Desktop.
Save AugustoCalaca/fa35600d3b2e63ecac4709aa6658c963 to your computer and use it in GitHub Desktop.
Styled Components and Material UI working on server side with nextjs
import React from 'react';
import { ServerStyleSheet } from 'styled-components';
import { ServerStyleSheets } from '@material-ui/core/styles';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(context) {
const styledComponentsSheet = new ServerStyleSheet();
const materialSheets = new ServerStyleSheets();
const originalRenderPage = context.renderPage;
try {
context.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />)),
});
const initialProps = await Document.getInitialProps(context);
return {
...initialProps,
styles: (
<React.Fragment>
{initialProps.styles}
{materialSheets.getStyleElement()}
{styledComponentsSheet.getStyleElement()}
</React.Fragment>
),
};
} finally {
styledComponentsSheet.seal();
}
}
render() {
return (
<Html>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment