Created
February 17, 2021 20:25
-
-
Save ludder/c29efcbd0aee813a914ddaf8a3d16496 to your computer and use it in GitHub Desktop.
Typed example of _document.js in Next.js with styled components as in: https://github.com/vercel/next.js/blob/master/examples/with-styled-components/pages/_document.js
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 Document, { DocumentContext, DocumentInitialProps } from "next/document"; | |
import { ReactElement } from "react"; | |
import { ServerStyleSheet } from "styled-components"; | |
interface InitialProps extends DocumentInitialProps { | |
styles: ReactElement; | |
} | |
export default class MyDocument extends Document { | |
static async getInitialProps(ctx: DocumentContext): Promise<InitialProps> { | |
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(); | |
} | |
} | |
} |
Thanks, worked for me! 🥇 👍
Thanks a million!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THANK YOU!! This worked like a charm as of today 💯