While aimlessly searching the depths of the internet for solutions to a perplexing error, I mistakenly executed a npm install
command on styled-components
due to a reference in this response on a Github issue. This mishap occurred as they presented an object similar to Material UI's ServerStyleSheet
(as opposed to Material UI's
ServerStyleSheets</code), which obviously did not yield any positive results.</p>
<p><strong>BUT.........</strong> In a twist of events, I decided to implement the <code>ServerStyleSheet
workaround to align it with Material UI's
ServerStyleSheets
object, resulting in the creation of a new
_document.js
.
I am still astonished at how I managed to adapt a completely different solution to resolve the issue successfully. After testing it, I can confirm that the problem has been fully rectified and page reloads function seamlessly.
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from "@material-ui/styles";
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
try{
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheet.collect(<App {...props}/>)
});
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
}
} finally {
ctx.renderPage(sheet)
}
}
render() {
return (
<Html>
<Head>
<link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
<style>{`body { margin: 0 } /* custom! */`}</style>
<meta name="viewport"content="width=device-width, initial-scale=1.0" />
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</Html>
)}
}
export default MyDocument;
If you want to witness the uncanny success story behind this fix, here is an alternative solution for the same error using styled-components
:
export default MyDocument;
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(<App {...props} />)
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
}
} finally {
sheet.seal()
}
}
}
I hope this account of my experience helps others navigate through the complexities of Material-UI + Next.js integration.