react

Step-by-step guidelines to implement Material UI in Next.js 2020

WK

William Kurniawan

Jul 24, 2020

In this article, I want to share how to integrate Material UI in Next.js applications. We will build a very basic website using Material UI and Next.js.

Prerequisites

I will assume that you have some familiarity with React, but you should be able to follow along even if you are coming from a different programming language. You will also need to have Node >= 8.10 and npm >= 5.6 on your machine.

Setup

Create a new directory called my-app:
mkdir my-app
Install next, react, and react-dom in your project directory:
cd my-app
yarn add -E next react react-dom
Install @types/node, @types/react, and typescript if you are going to use TypeScript in your project:
yarn add -DE @types/node @types/react typescript
Open package.json and add the following scripts:
"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
}

Install Material UI

Install @material-ui/core in your project directory:
yarn add -E @material-ui/core
Create a theme configuration file utils/theme.ts:
mkdir utils
touch utils/theme.ts
And, put the following code in the theme configuration file:
import indigo from '@material-ui/core/colors/indigo';
import pink from '@material-ui/core/colors/pink';
import { createMuiTheme } from '@material-ui/core/styles';

const theme = createMuiTheme({
  palette: {
    primary: indigo,
    secondary: pink,
  },
});

export default theme;
Create a custom document page pages/_document.tsx:
import React from 'react';
// Modules
import Document, { Html, Head, Main, NextScript } from 'next/document';
// MUI Core
import { ServerStyleSheets } from '@material-ui/core/styles';
// Utils
import theme from '../utils/theme';

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/css2?family=Open+Sans:wght@300;400;600;700&display=swap" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with server-side generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
  // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render

  // Render app and page and get the context of the page with collected side effects.
  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 page rendering finish.
    styles: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement(),
    ],
  };
};

export default MyDocument;
Create a custom app page pages/_app.tsx:
import React from 'react';
// Modules
import { AppProps } from 'next/app';
import Head from 'next/head';
// MUI Core
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/core/styles';
// Utils
import theme from '../utils/theme';

const MyApp: React.FC<AppProps> = ({ Component, pageProps }) => {
  React.useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles && jssStyles.parentElement) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  return (
    <>
      <Head>
        <title>My App</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Component {...pageProps} />
        </ThemeProvider>
    </>
  );
};

export default MyApp;
Create the home page page/index.tsx:
import React from 'react';
// Modules
import { NextPage } from 'next/types';

const HomePage: NextPage = () => {
  return (
    <Button color="primary" variant="contained">My App</Button>
  );
};

export default HomePage;

Start the Development Server

To start the development server, run this command in your terminal:
yarn dev
You can access your development server at http://localhost:3000, and you will see a Material UI button!
To understand more about Material UI and Next.js, you can visit their official websites:

Copyright © 2020 William Kurniawan. All rights reserved.