refactor: change document template to use material-ui during SSR

main
Josue 4 years ago committed by Tsu-ba-me
parent fa7084f5c4
commit a552028e80
  1. 50
      striker-ui/pages/_document.tsx

@ -1,34 +1,18 @@
import { Children } from 'react'; import Document, { DocumentInitialProps, DocumentContext } from 'next/document';
import Document, { Html, Head, Main, NextScript } from 'next/document'; import { ServerStyleSheets as MaterialUiServerStyleSheets } from '@material-ui/styles';
import { ServerStyleSheets } from '@material-ui/core/styles'; // import { ServerStyleSheet as StyledComponentSheets } from 'styled-components';
export default class MyDocument extends Document { class MyDocument extends Document {
render(): JSX.Element { static async getInitialProps(
return ( ctx: DocumentContext,
<Html lang="en"> ): Promise<DocumentInitialProps> {
<Head> const materialUiSheets = new MaterialUiServerStyleSheets();
<meta charSet="utf-8" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with server-side generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
// Render app and page and get the context of the page with collected side effects.
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage; const originalRenderPage = ctx.renderPage;
ctx.renderPage = () => ctx.renderPage = () =>
originalRenderPage({ originalRenderPage({
enhanceApp: (App) => (props) => enhanceApp: (App) => (props) =>
sheets.collect( materialUiSheets.collect(
<App <App
/* eslint-disable react/jsx-props-no-spreading */ /* eslint-disable react/jsx-props-no-spreading */
{...props} {...props}
@ -40,10 +24,14 @@ MyDocument.getInitialProps = async (ctx) => {
return { return {
...initialProps, ...initialProps,
// Styles fragment is rendered after the app and page rendering finish. styles: (
styles: [ <>
...Children.toArray(initialProps.styles), {initialProps.styles}
sheets.getStyleElement(), {materialUiSheets.getStyleElement()}
], </>
}; ),
}; };
}
}
export default MyDocument;

Loading…
Cancel
Save