Last active
December 28, 2020 07:33
-
-
Save raflyfahrezi/9908a5abc76509cbe4808c41b678cd75 to your computer and use it in GitHub Desktop.
_document.js configuration when using Styled Components in Next.js
This file contains hidden or 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 Document from 'next/document' | |
import { ServerStyleSheet } from 'styled-components' | |
export default class MyDocument extends Document { | |
static async getInitialProps(ctx) { | |
const sheet = new ServerStyleSheet() | |
const originalRenderPage = ctx.renderPage | |
try { | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceApp: App => props => | |
sheet.collectStyles(<App {...props} />), | |
}) | |
const initialProps = await Document.getInitialProps(ctx) | |
return { | |
...initialProps, | |
styles: ( | |
<> | |
{initialProps.styles} | |
{sheet.getStyleElement()} | |
</> | |
), | |
} | |
} finally { | |
sheet.seal() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment