Skip to content

Instantly share code, notes, and snippets.

@Danetag
Last active March 27, 2020 02:59
Show Gist options
  • Save Danetag/800e1281a8e58a05cdd5de2caeeab4d1 to your computer and use it in GitHub Desktop.
Save Danetag/800e1281a8e58a05cdd5de2caeeab4d1 to your computer and use it in GitHub Desktop.
Emotion extractCritical() with NextJS
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;
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