Skip to content

Instantly share code, notes, and snippets.

@homfarnam
Created March 3, 2021 11:05
Show Gist options
  • Save homfarnam/454ea12d23e5a386a1f6295bf045aca4 to your computer and use it in GitHub Desktop.
Save homfarnam/454ea12d23e5a386a1f6295bf045aca4 to your computer and use it in GitHub Desktop.
Next Js _document.js - styled component
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
@hamza4600
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment