Last active
March 27, 2020 02:59
-
-
Save Danetag/800e1281a8e58a05cdd5de2caeeab4d1 to your computer and use it in GitHub Desktop.
Emotion extractCritical() with NextJS
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 React from "react"; | |
import App from "next/app"; | |
import Head from "next/head"; | |
import createCache from '@emotion/cache' | |
import { CacheProvider } from '@emotion/core' | |
const cache = createCache() | |
class MyApp extends App { | |
render() { | |
const { Component, pageProps } = this.props; | |
return ( | |
<CacheProvider value={cache}> | |
<Head /> | |
<Component {...pageProps} /> | |
</CacheProvider> | |
); | |
} | |
} | |
export default MyApp; |
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, { Html, Head, Main, NextScript } from 'next/document' | |
import { CacheProvider } from '@emotion/core' | |
import createEmotionServer from 'create-emotion-server' | |
import createCache from '@emotion/cache' | |
class MyDocument extends Document { | |
static async getInitialProps(ctx) { | |
const originalRenderPage = ctx.renderPage | |
const cache = createCache() | |
const { extractCritical } = createEmotionServer(cache) | |
// rebuild the renderPage with the provider | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceApp: App => props => <CacheProvider value={cache}><App {...props} /></CacheProvider> | |
}) | |
const { html, head } = ctx.renderPage() | |
let { css, ids } = extractCritical(html); | |
return { | |
html, | |
head, | |
// styles will automatically be added in the <head/> by next | |
styles: ( | |
<> | |
<style data-emotion-css={ids.join(' ')}>{css}</style> | |
</> | |
) | |
} | |
} | |
render() { | |
return ( | |
<Html lang="en-US"> | |
<Head /> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
) | |
} | |
} | |
export default MyDocument |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment