Last active
August 3, 2022 16:17
-
-
Save umkl/5cf77cdf816bee0d663138bf67c02b09 to your computer and use it in GitHub Desktop.
nextjs styled-components missing style on reload issue
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, { Head, Html, Main, NextScript } from "next/document"; | |
import { ServerStyleSheet } from "styled-components"; | |
export default class MyDocument extends Document { | |
static async getInitialProps(ctx) { | |
const sheet = new ServerStyleSheet(); | |
const originalRenderPage = ctx.renderPage; | |
try { | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceApp: (App) => (props) => | |
sheet.collectStyles(<App {...props} />), | |
}); | |
const initialProps = await Document.getInitialProps(ctx); | |
return { | |
...initialProps, | |
styles: ( | |
<> | |
{initialProps.styles} | |
{sheet.getStyleElement()} | |
</> | |
), | |
}; | |
} finally { | |
sheet.seal(); | |
} | |
} | |
render() { | |
return ( | |
<Html> | |
<Head> | |
{/* styled-components styles */} | |
{this.props.styles} | |
</Head> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Due to the fact that nextjs doesnt fetch styles before rendering the page, this configuration is necessary for using styled-components. Even though nextjs provides a solution to that on their official github repository, I had to reconfigure it in order to be able to manipulate my html scaffold alongside.