Skip to content

Instantly share code, notes, and snippets.

@Brlaney
Created July 21, 2021 00:05
Show Gist options
  • Save Brlaney/90fa3602e329868f5e45b717995391b8 to your computer and use it in GitHub Desktop.
Save Brlaney/90fa3602e329868f5e45b717995391b8 to your computer and use it in GitHub Desktop.
My _document.tsx file for using Material-UI with Next.js
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