Created
July 21, 2021 00:05
-
-
Save Brlaney/90fa3602e329868f5e45b717995391b8 to your computer and use it in GitHub Desktop.
My _document.tsx file for using Material-UI with Next.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 * as React from 'react' | |
import Document, { Html, Head, Main, NextScript } from 'next/document' | |
import createEmotionServer from '@emotion/server/create-instance' | |
import createCache from '@emotion/cache' | |
import { CacheProvider } from '@emotion/react' | |
function getCache() { | |
const cache = createCache({ key: 'css', prepend: true }) | |
cache.compat = true | |
return cache | |
} | |
export default class CustomDocument extends Document { | |
render () { | |
return ( | |
<Html lang='en'> | |
<Head /> | |
<body> | |
<Main /> | |
</body> | |
<NextScript /> | |
</Html> | |
) | |
} | |
} | |
CustomDocument.getInitialProps = async (ctx) => { | |
const originalRenderPage = ctx.renderPage | |
const cache = getCache() | |
const { extractCriticalToChunks } = createEmotionServer(cache) | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceComponent: (Component) => (props) => | |
( | |
<CacheProvider value={cache}> | |
<Component {...props} /> | |
</CacheProvider> | |
), | |
}) | |
const initialProps = await Document.getInitialProps(ctx) | |
const emotionStyles = extractCriticalToChunks(initialProps.html) | |
const emotionStyleTags = emotionStyles.styles.map((style) => ( | |
<style | |
data-emotion={`${style.key} ${style.ids.join(' ')}`} | |
key={style.key} | |
// eslint-disable-next-line react/no-danger | |
dangerouslySetInnerHTML={{ __html: style.css }} | |
/> | |
)) | |
return { | |
...initialProps, | |
styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags], | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment