Created
June 2, 2022 02:52
-
-
Save kmvan/c97f0ae04ab59af23b10d0c5745eeb34 to your computer and use it in GitHub Desktop.
Next 12 + React 18 _document.tsx
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, | |
Head, | |
Html, | |
Main, | |
NextScript, | |
} from 'next/document' | |
import { CSSProperties, ServerStyleSheet } from 'styled-components' | |
import { AppContextProps } from 'YOUR APP CONTEXT' | |
interface PageDocumentProps { | |
__NEXT_DATA__: { | |
props: { | |
appProps: AppContextProps | |
} | |
} | |
} | |
export default function PageDocument({ | |
__NEXT_DATA__: { | |
props: { appProps }, | |
}, | |
}: PageDocumentProps) { | |
return ( | |
<Html lang={appProps.lang}> | |
<Head /> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
) | |
} | |
PageDocument.getInitialProps = async (ctx: DocumentContext) => { | |
const styledComponentsSheet = new ServerStyleSheet() | |
const originalRenderPage = ctx.renderPage | |
try { | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceApp: (App) => (props) => { | |
return styledComponentsSheet.collectStyles(<App {...props} />) | |
}, | |
}) | |
const initialProps = await Document.getInitialProps(ctx) | |
initialProps.styles = [ | |
initialProps.styles, | |
styledComponentsSheet.getStyleElement(), | |
] | |
return initialProps | |
} finally { | |
styledComponentsSheet.seal() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment