Created
April 15, 2020 12:10
-
-
Save wwiechorek/5f5441be878f866e51b0c6f04a9c11a1 to your computer and use it in GitHub Desktop.
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 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