styled-components-website
styled-components-website copied to clipboard
Add FAQ on NextJS 13 usage
I have this working without any of the Registry stuff from the Beta Next Docs, just with the following in my
next.config.js, but I'm getting a flash of unstyled content because we're seeing the server rendered version for a second before its hydrated. Anyone found a way around this?compiler: { styledComponents: true, }Edit:
Using the registry and including an empty
<head>in your layout seems to render everything nicely, and avoids any flash of unstyled content:export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html> <head></head> <body> <StyledComponentsRegistry>{children}</StyledComponentsRegistry> </body> </html> ); }
this solution works for me, I didn't need to use an empty 'head' tag for those who couldn't, make sure your global styles are also inside the registry, ex:
<StyledComponentsRegistry>
<GlobalStyles />
{children}
</StyledComponentsRegistry>
Thank you! @andflett
Originally posted by @matheuskroska in https://github.com/styled-components/styled-components/issues/3856#issuecomment-1562210779
@andflett If you're interested in contributing a FAQ page for this, you'd want to make a sibling md(x) to this doc: https://github.com/styled-components/styled-components-website/blob/main/sections/faqs/nesting.mdx
And then add an entry to the sidebar matching your H2 text here: https://github.com/styled-components/styled-components-website/blob/c623f3d0be7b300572583cdac7ed3ab3e2bb0668/pages/docs.json
For me, this config works without any issues so far on Next 13.
- Inside
_document.jsor_document.tsxadd the following:
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
DocumentInitialProps,
} from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class CustomDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const originalRenderPage = ctx.renderPage;
const sheet = new ServerStyleSheet();
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
enhanceComponent: (Component) => Component,
});
const intialProps = await Document.getInitialProps(ctx);
const styles = sheet.getStyleElement();
return { ...intialProps, styles };
}
render() {
return (
<Html>
<Head>{this.props.styles}</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
- Inside
next.config.jsadd:
compiler: {
styledComponents: true,
},
The configuration provided is intended to address the issue of style flashing or disappearing when refreshing pages in Next.js 13 with styled-components. By including the code inside the _document.js or _document.tsx file and adding the configuration in the next.config.js file, the styles should remain consistent and not flicker or disappear during page transitions or refreshes. Hopefully, this can help, and not sure if it was posted before.