I am converting my React app into Next app to take advantage of SSR. I am using Material ui 4 for styling.
I have implemented _app.js and _document.js file as per the Material ui documentation but the problem is when the page is loaded for the first time, material ui styles are not being applied but when I make some changes in my components then only all the styles appear.
I am posting this question only after referring this, this answers and other resources on internet
_app.js
import '@assets/fonts/global.css';
import React, {useState, useEffect} from "react";
import Layout from "@layout/Layout";
import Footer from "@layout/Footer/Footer";
import Header from "@layout/Header/Header";
//import Sidebar from "@layout/Sidebar/Sidebar";
//Material UI
import CssBaseline from "@material-ui/core/CssBaseline";
import theme from "@helper/theme/theme";
import {ThemeProvider as MuiThemeProvider} from "@material-ui/styles";
//Redux
import {wrapper} from "@store/store";
function MyApp({Component, pageProps}) {
React.useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []);
return (
<>
<MuiThemeProvider theme={theme}>
<CssBaseline/>
<Header/>
<Layout>
<Component {...pageProps} />
</Layout>
<Footer/>
</MuiThemeProvider>
</>
);
}
export default wrapper.withRedux(MyApp);
_document.js
import React from 'react';
import Document, {Html, Head, Main, NextScript} from 'next/document';
import {ServerStyleSheets} from '@material-ui/core/styles';
import theme from "@helper/theme/theme";
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<meta name="theme-color" content={theme.palette.primary.main} />
</Head>
<body>
<Main/>
<NextScript/>
</body>
</Html>
);
}
}
MyDocument.getInitialProps = async (ctx) => {
console.log('DOC Called');
// 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: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
};
};
Note: Even after using _app.js and _document.js file as per the Material ui documentation I'm still getting the following warning in console
next-dev.js?3515:25 Warning: Prop `className` did not match.