Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

problem with Next.js and @material-ui.

//It's a problem with Next.js and @material-ui. The problem has something to do with SSR (Server Side Rendering) so you have to cancel it and remove the server side files.

//step 1: create _document.js under pages folder

//step 2: add this to the documents file

import { ServerStyleSheets } from '@mui/styles';
import Document, { Head, Html, NextScript, Main } from 'next/document';
import React from 'react';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head></Head>
        <body>
          <Main></Main>
          <NextScript></NextScript>
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;
  ctx.renderPage = () => {
    return originalRenderPage({
      enchanceApp: (App) => (props) => sheets.collect(<App {...props} />),
    });
  };
  const initialProps = await Document.getInitialProps(ctx);
  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement(),
    ],
  };
};

//step 3: inside the _app.js add this inside the main function component

  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) jssStyles.parentElement.removeChild(jssStyles);
  }, []);

//restart the Next.js app and you're done
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #problem
ADD COMMENT
Topic
Name
4+6 =