Skip to content

Instantly share code, notes, and snippets.

@wwiechorek
Created April 15, 2020 12:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwiechorek/5f5441be878f866e51b0c6f04a9c11a1 to your computer and use it in GitHub Desktop.
Save wwiechorek/5f5441be878f866e51b0c6f04a9c11a1 to your computer and use it in GitHub Desktop.
import Document, { Head, Main, NextScript } from 'next/document';
// Import styled components ServerStyleSheet
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static getInitialProps({ renderPage, req }) {
// Step 1: Create an instance of ServerStyleSheet
const sheet = new ServerStyleSheet();
// Step 2: Retrieve styles from components in the page
const page = renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />),
);
// Step 3: Extract the styles as <style> tags
const styleTags = sheet.getStyleElement();
// Step 4: Pass styleTags as a prop
return { ...page, styleTags, url: req.url };
}
render() {
return (
<html>
<Head>
<title>Page title</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon" />
{/* Step 5: Output the styles in the head */}
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment