Created
March 3, 2021 11:05
-
-
Save homfarnam/454ea12d23e5a386a1f6295bf045aca4 to your computer and use it in GitHub Desktop.
Next Js _document.js - styled component
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 { ServerStyleSheet, createGlobalStyle } from "styled-components" | |
const GlobalStyle = createGlobalStyle` | |
body { | |
padding: 0; | |
margin: 0; | |
} | |
` | |
class MyDocument extends Document { | |
static async getInitialProps(ctx) { | |
const sheet = new ServerStyleSheet() | |
const originalRenderPage = ctx.renderPage | |
try { | |
ctx.renderPage = () => | |
originalRenderPage({ | |
// useful for wrapping the whole react tree | |
enhanceApp: (App) => (props) => | |
sheet.collectStyles( | |
<> | |
<GlobalStyle /> | |
<App {...props} /> | |
</> | |
), | |
// useful for wrapping in a per-page basis | |
enhanceComponent: (Component) => Component, | |
}) | |
// Run the parent `getInitialProps`, it now includes the custom `renderPage` | |
const initialProps = await Document.getInitialProps(ctx) | |
return { | |
...initialProps, | |
styles: ( | |
<> | |
{initialProps.styles} | |
{sheet.getStyleElement()} | |
</> | |
), | |
} | |
} finally { | |
sheet.seal() | |
} | |
} | |
render() { | |
return ( | |
<Html lang="en"> | |
<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
Thanks