From 7ce5d3f2408b08c6121b7edd825615161c616309 Mon Sep 17 00:00:00 2001 From: chemicalkosek Date: Thu, 10 Mar 2022 19:12:23 +0100 Subject: [PATCH] Re-add _document to with-styled-components example (#35163) `_document.js` was removed from the styled components swc example I have tested with and without the custom `_document.js` Unfortunately without `_document.js` there is FOUC (Flash of unstyled content) on initial request. ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md` ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. - [ ] Errors have helpful link attached, see `contributing.md` ## Documentation / Examples - [ ] Make sure the linting passes by running `yarn lint` Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com> --- .../with-styled-components/pages/_document.js | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 examples/with-styled-components/pages/_document.js diff --git a/examples/with-styled-components/pages/_document.js b/examples/with-styled-components/pages/_document.js new file mode 100644 index 000000000000..2a59afeb93c1 --- /dev/null +++ b/examples/with-styled-components/pages/_document.js @@ -0,0 +1,30 @@ +import Document 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(), + }) + + const initialProps = await Document.getInitialProps(ctx) + return { + ...initialProps, + styles: ( + <> + {initialProps.styles} + {sheet.getStyleElement()} + + ), + } + } finally { + sheet.seal() + } + } +}