Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI breaks after refreshing

I am using material UI with Next.js. I am running onnpm run dev. My problem is that the styling on the site completely breaks whenever I press the reloading button on the browser. Is this normal behavior? Seems like Material-UI stops working.

Here is my code.

I have an index.js and a component.

index

import React, { Component } from 'react'
import CssBaseline from '@material-ui/core/CssBaseline';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import AppBar from '../components/NavBar/NavBar';

const theme = createMuiTheme({
  palette: {
      primary: {
        main: '#f28411',
      },
  },
});


class App extends Component {
  render() {
    return (
        <MuiThemeProvider theme={theme}>
        <React.Fragment>
            <CssBaseline />
            <AppBar />
        </React.Fragment>
        </MuiThemeProvider>
    )
  }
}
export default App

component

import React, { Component } from 'react'
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'

class NavBar extends Component {
    render() {
        const { classes } = this.props;

        return(
            <div>
            <AppBar position="static">
                <Toolbar>
                    <Typography variant="title" color="inherit">
Test                        
</Typography>
                </Toolbar>
            </AppBar>
            </div>
        );
    }
}

const styles = theme => ({
  title: {
    color: '#FFF',
  },
});

NavBar.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NavBar);
like image 407
carloscc Avatar asked Aug 19 '18 01:08

carloscc


3 Answers

I had this same issue but was not using styled-components so the above answer did not apply, so I thought I would post in case this helps anyone else. To fix this, I just had to add the _document.js file under the pages/ directory included in the material-ui sample:

import React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheets } from '@material-ui/core/styles'
import theme from '../shared/utils/theme'

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang='en'>
        <Head>
          <meta name='theme-color' content={theme.palette.primary.main} />
          <link
            rel='stylesheet'
            href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap'
          />
        </Head>
        <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: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement(),
    ],
  }
}
like image 153
mlz7 Avatar answered Oct 02 '22 16:10

mlz7


It could be possible that you need a babel plugin for this.

In your package, add

npm install --save-dev babel-plugin-styled-components

In your .babelrc, add

{
  "plugins": [
    [ "styled-components", { "ssr": true, "displayName": true, "preprocess": false } ]
  ]
}

Let me know if this works.

like image 23
dkulkarni Avatar answered Oct 02 '22 14:10

dkulkarni


As it turns out, you cannot use all of the third-party libraries for Next JS in the same way as you would use for React apps. You need to modify your pages/_document.js and pages/_app.js. Also, you will need theme.js for configuring Material UI colors and other default styles. You can include theme.js to any folder, in my case it is in helpers folder.

  1. _app.js
import React from "react";
import App from "next/app";
import theme from '../helpers/theme';  // needed for Material UI
import CssBaseline from '@material-ui/core/CssBaseline';
import {ThemeProvider} from '@material-ui/core/styles';


class MyApp extends App {

   static async getInitialProps({Component, ctx}) {
      const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};
      //Anything returned here can be accessed by the client
      return {pageProps: pageProps};
   }

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

      return (
          <ThemeProvider theme={theme}>
             <CssBaseline />
              {/* default by next js */}
              <Component {...pageProps}/>
          </ThemeProvider>
      )
   }
}

export default MyApp
  1. _document.js
import Document, {Html, Head, Main, NextScript} from "next/document";
import theme from '../helpers/theme';
import { ServerStyleSheets } from '@material-ui/core/styles';
import React from "react";

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

      return props;
   }

   render() {
      return (
          <Html>
             <Head>
                <meta name="theme-color" content={theme.palette.primary.main} />
             </Head>
             <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()],
   };
};
  1. theme.js
import { createMuiTheme } from '@material-ui/core/styles';
import { red } from '@material-ui/core/colors';

// Create a theme instance.
const theme = createMuiTheme({
   palette: {
      primary: {
         main: '#FFF212',
      },
      secondary: {
         main: '#FFF212',
      },
      error: {
         main: red.A400,
      },
      background: {
         default: '#fff',
      },
   },
});

export default theme;

There is an amazing repository in Github https://github.com/vercel/next.js/tree/canary/examples There you can find a list of libraries with the correct way of using them in Next JS apps.

For your case here is the link: https://github.com/vercel/next.js/tree/canary/examples/with-material-ui.

like image 40
Ismoil Shokirov Avatar answered Oct 02 '22 16:10

Ismoil Shokirov