Ismoil Shokirov
Ismoil Shokirov

Reputation: 3011

How to connect Material UI v5 to Next JS v12?

Recently, Material UI 5 was released. Previously (in Material UI 4), I used to connect it by modifying _document.js and _app.js. Is it the same for Material UI 5?

for MUI v4 _app.js

import CssBaseline from '@material-ui/core/CssBaseline';
import {ThemeProvider} from '@material-ui/core/styles';

class MyApp extends App {

   render() {
      const {Component, pageProps, router} = this.props;

      return (
          <ThemeProvider>
             <CssBaseline />
              <Component {...pageProps}/>
          </ThemeProvider>
      )
   }
}

export default MyApp

for MUI v4 _document.js

import Document, {Html, Main, NextScript} from "next/document";
import { ServerStyleSheets } from '@material-ui/core/styles';

export default class MyDocument extends Document {
   static async getInitialProps(ctx) {
      const initialProps = await Document.getInitialProps(ctx);
      let props = {...initialProps};

      return props;
   }

   render() {
      return (
          <Html>
             <body>
             <Main/>
             <NextScript/>
             </body>
          </Html>
      );
   }
}


MyDocument.getInitialProps = async (ctx) => {
   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 register rendering finish.
      styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
   };
};

What I want to ask is: Should I connect it in the same way to MUI v5?

Maybe there is a more elegant way to do it?

Upvotes: 2

Views: 1516

Answers (2)

Ismoil Shokirov
Ismoil Shokirov

Reputation: 3011

It is connected still the same way as I provided in my question, by some changes in _app.js and _document.js

Official MUI example with Next js

https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs

Upvotes: 2

Mark Williams
Mark Williams

Reputation: 381

If it's just css you're importing from @materail-ui/core/styles, you can simply import the CSS directly in your _App.js with...

import '@materail-ui/core/styles/someFilename.css' (no from needed) And it should be accessible anywhere in your app from there.

Upvotes: 0

Related Questions