Skip to content

Commit

Permalink
Modified _app and _document to ensure matching styling between client…
Browse files Browse the repository at this point in the history
… and server
  • Loading branch information
tonyvugithub committed Jan 17, 2021
1 parent 3096095 commit 1849fa7
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ module.exports = {
{
files: ['src/frontend/next/**/*.ts', 'src/frontend/next/**/*.tsx'],
plugins: ['@typescript-eslint'],
env: {
browser: true,
},
rules: {
'react/prop-types': 'off',
'react/react-in-jsx-scope': 'off',
Expand Down
10 changes: 10 additions & 0 deletions src/frontend/next/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { useEffect } from 'react';
import { AppProps } from 'next/app';
import '../styles/globals.css';

// Reference: https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_app.js
const App = ({ Component, pageProps }: AppProps) => {
// This hook is for ensuring the styling is sync between client and server
useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement?.removeChild(jssStyles);
}
}, []);
return <Component {...pageProps} />;
};

Expand Down
44 changes: 44 additions & 0 deletions src/frontend/next/src/pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Children } from 'react';
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';

// Reference: https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}

render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

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;

ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
});

const initialProps = await Document.getInitialProps(ctx);

return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [...Children.toArray(initialProps.styles), sheets.getStyleElement()],
};
};

export default MyDocument;

0 comments on commit 1849fa7

Please sign in to comment.