Skip to content

Commit f4f7978

Browse files
committed
fix bug where unstyled html loaded before styles
update code in _document.js to enable server-side style rendering
1 parent c561266 commit f4f7978

File tree

1 file changed

+63
-16
lines changed

1 file changed

+63
-16
lines changed

pages/_document.js

Lines changed: 63 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,65 @@
1-
import { Html, Head, Main, NextScript } from 'next/document';
1+
import Document, { Html, Head, Main, NextScript } from 'next/document';
2+
import { ServerStyleSheet } from 'styled-components';
23

3-
export default function Document() {
4-
return (
5-
<Html>
6-
<Head>
7-
<link
8-
rel='stylesheet'
9-
href='https://fonts.googleapis.com/css2?family=Assistant:wght@400;700&family=Open+Sans:wght@700&display=swap'
10-
/>
11-
</Head>
12-
<body>
13-
<Main />
14-
<NextScript />
15-
</body>
16-
</Html>
17-
);
4+
// export default function Document() {
5+
// return (
6+
// <Html>
7+
// <Head>
8+
// <link
9+
// rel='stylesheet'
10+
// href='https://fonts.googleapis.com/css2?family=Assistant:wght@400;700&family=Open+Sans:wght@700&display=swap'
11+
// />
12+
// </Head>
13+
// <body>
14+
// <Main />
15+
// <NextScript />
16+
// </body>
17+
// </Html>
18+
// );
19+
// }
20+
21+
class MyDocument extends Document {
22+
static async getInitialProps(ctx) {
23+
const sheet = new ServerStyleSheet();
24+
const originalRenderPage = ctx.renderPage;
25+
26+
try {
27+
ctx.renderPage = () =>
28+
originalRenderPage({
29+
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
30+
});
31+
32+
const initialProps = await Document.getInitialProps(ctx);
33+
return {
34+
...initialProps,
35+
styles: (
36+
<>
37+
{initialProps.styles}
38+
{sheet.getStyleElement()}
39+
</>
40+
),
41+
};
42+
} finally {
43+
sheet.seal();
44+
}
45+
}
46+
47+
render() {
48+
return (
49+
<Html>
50+
<Head>
51+
<link
52+
rel='stylesheet'
53+
href='https://fonts.googleapis.com/css2?family=Assistant:wght@400;700&family=Open+Sans:wght@700&display=swap'
54+
/>
55+
</Head>
56+
<body>
57+
<Main />
58+
<NextScript />
59+
</body>
60+
</Html>
61+
);
62+
}
1863
}
64+
65+
export default MyDocument;

0 commit comments

Comments
 (0)