Rodrigo Assis Neves
Rodrigo Assis Neves

Reputation: 150

Material UI and Next.js setup

It seems like the "way to go" for setting up Next.js and MUI is to remove the server-side styling, so I did it in _app.tsx

import '../styles/globals.css';
import type { AppProps } from 'next/app';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement?.removeChild(jssStyles);
    }
  }, []);
  return <Component {...pageProps} />;
}

export default MyApp;

also did it in _document.tsx

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

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

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

But it's still not working, Material UI change with makeStyles doesn't take effect. The jssStyles variable is always null as well, so that's probably the problem, but I can't find a solution.

Upvotes: 3

Views: 2893

Answers (1)

Youzef
Youzef

Reputation: 838

The best way to go about this would be to clone the example repo from mui github then start from there. If not then just go over their _app.tsx and _document.tsx and make sure you have all the dependencies installed. Notice they also use the @emotion package.

Javascript repo link here and Typescript repo here

Upvotes: 6

Related Questions