Created
July 21, 2020 17:41
-
-
Save AugustoCalaca/fa35600d3b2e63ecac4709aa6658c963 to your computer and use it in GitHub Desktop.
Styled Components and Material UI working on server side with nextjs
This file contains 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 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