NashTech Insights

How to integrate mui with nextjs app

Pushpendra
Pushpendra
Table of Contents
pexels-photo-360438.jpeg

Introduction

In today’s web development creating aesthetically pleasing and user-friendly interfaces is a top priority. Material-UI, a popular React component library that follows the Material Design guidelines, offers a vast collection of pre-designed UI elements. When combined with Nextjs, a powerful React framework for building server-rendered applications, you can create visually stunning and highly performant web applications. In this blog post, we will explore the process of integrating Material-UI with a Nextjs app, enabling you to leverage the best of both worlds.

Prerequisites

Before diving into the integration process, it’s important to have a basic understanding of React and Next.js. Familiarity with JavaScript, JSX syntax, and npm (Node Package Manager) is also recommended. Additionally, ensure that you have a working Next.js project set up.

Step 1: Install Material-UI and Required Dependencies

To begin, navigate to your Next.js project’s root directory in the terminal and install Material-UI and its required dependencies by running the following command:
npm install @mui/material @emotion/react @emotion/styled
This command installs the Material-UI core library, along with the necessary dependencies for styling with emotion.

Step 2: Set Up the Custom Document

Nextjs provides a custom Document component that allows you to augment the server-rendered HTML. To enable server-side rendering of Material-UI styles, create a custom _document.js file in the pages directory (if it doesn’t already exist) with the following code:

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

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          {/* Meta tags, favicon, etc. */}
        </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(),
    ],
  };
};

Step 3: Create a Custom App

Nextjs allows you to override the default App component and add custom behavior. In the pages/_app.js file (create one if it doesn’t exist), add the following code:

Step 4: Import and Use Material-UI Components

import React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';

const cache = createCache({ key: 'css', prepend: true });

function MyApp({ Component, pageProps }) {
  return (
    <CacheProvider value={cache}>
      <ThemeProvider>
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  );
}

export default MyApp;
Nextjs-mui

With the setup complete, you can now import and use Material-UI components in your Nextjs pages or components. For example, create a new file called pages/index.js

Conclusion

In this blog we learn how to integrate MUI with next js web app but the more we will practice will give the clear idea of how it works, So keep Practicing.

Follow us on LinkedIn for more such updates: Front-end Competency

Pushpendra

Pushpendra

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: