Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How to use Material-UI with Next.js ?
Next article icon

How to use Material-UI with Next.js ?

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Integrating Material-UI (now known as MUI) with Next.js allows you to build modern, responsive user interfaces with a comprehensive set of React components. In this article, we will learn some additional necessary steps to be performed to integrate Material-UI with the Next.js project.

Prerequisites:

  • Node.js and NPM
  • Next.js

Approach

To use the Material-UI with Next.js we have to wrap the complete app with the ThemeProvider for consistent theming, using Material-UI components in your pages, and ensuring server-side rendering support with Emotion’s styling solutions for optimized performance and consistent styling.

First Let's start by creating a Next.js project.

Steps to Integrate Material UI with Next.js

Step 1: Initialize a nwe Next.js project using the following command:

npx create-next-app gfg-next-mui

Step 2: Move to the Project directory

cd gfg-next-mui

Step 3: Install Material-UI

To install the dependencies and save them in your package.json file, run:

npm install @mui/material @emotion/react @emotion/styled @emotion/server

Project Structure:

It will look like this.

Project Structure

The updated dependencies in the package.json file are:

"dependencies": {
"@emotion/react": "^11.13.0",
"@emotion/server": "^11.11.0",
"@emotion/styled": "^11.13.0",
"@mui/material": "^5.16.5",
"next": "14.2.4",
"react": "^18",
"react-dom": "^18"
}

Step 4: Modify the _document.js file. Configure the next app for server-side rendering using the Material UI and emotion library.

JavaScript
// pages/_document.js  import * as React from 'react'; import Document, { Html, Head, Main, NextScript } from 'next/document'; import createEmotionServer from '@emotion/server/create-instance'; import theme from '../src/theme'; import createEmotionCache from '../src/createEmotionCache';  export default class MyDocument extends Document {     render() {         return (             <Html lang="en">                 <Head>                     {/* PWA primary color */}                     <meta name="theme-color"                          content={theme.palette.primary.main} />                     <link rel="shortcut icon"                          href="/static/favicon.ico" />                     <link                         rel="stylesheet"                         href= "https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"                     /> {/* Inject MUI styles first to match with the prepend: true configuration. */}                     {this.props.emotionStyleTags}                 </Head>                 <body>                     <Main />                     <NextScript />                 </body>             </Html>         );     } }  // `getInitialProps` belongs to `_document` (instead of `_app`), // it's compatible with static-site generation (SSG). MyDocument.getInitialProps = async (ctx) => {         const originalRenderPage = ctx.renderPage;      // You can consider sharing the same emotion cache between      // all the SSR requests to speed up performance.     // However, be aware that it can have global side effects.        const cache = createEmotionCache();     const { extractCriticalToChunks } = createEmotionServer(cache);      ctx.renderPage = () =>         originalRenderPage({             enhanceApp: (App) =>                 function EnhanceApp(props) {                     return <App emotionCache={cache} {...props} />;                 },         });      const initialProps = await Document.getInitialProps(ctx);      // This is important. It prevents emotion to render invalid HTML.     // See  // https://github.com/mui-org/material-ui/issues/26561#issuecomment-855286153          const emotionStyles = extractCriticalToChunks(initialProps.html);     const emotionStyleTags = emotionStyles.styles.map((style) => (         <style             data-emotion={`${style.key} ${style.ids.join(' ')}`}             key={style.key}              // eslint-disable-next-line react/no-danger             dangerouslySetInnerHTML={{ __html: style.css }}         />     ));      return {         ...initialProps,         emotionStyleTags,     }; }; 

Step 5: Define Material-UI theme with custom primary, secondary, and error colors using createTheme from @mui/material/styles.

Create an src folder, add theme.js and createEmotionCache.js files as below

JavaScript
// Filename - src/theme.js  import { createTheme } from "@mui/material/styles"; import { red } from "@mui/material/colors";  // Create a theme instance. const theme = createTheme({     palette: {         primary: {             main: "#556cd6",         },         secondary: {             main: "#19857b",         },         error: {             main: red.A400,         },     }, });  export default theme; 
JavaScript
// Filename - src/createEmotionCache.js  import createCache from '@emotion/cache';  export default function createEmotionCache() {     return createCache({ key: 'css', prepend: true }); } 

Step 5: Update the file /pages/_app.js with the below code

JavaScript
// Filename - pages/_app.js  import * as React from "react"; import PropTypes from "prop-types"; import Head from "next/head"; import { ThemeProvider } from "@mui/material/styles"; import CssBaseline from "@mui/material/CssBaseline"; import { CacheProvider } from "@emotion/react"; import theme from "../src/theme"; import createEmotionCache from "../src/createEmotionCache";  // Client-side cache shared for the whole session // of the user in the browser.  const clientSideEmotionCache = createEmotionCache();  export default function MyApp(props) {     const { Component,     		emotionCache = clientSideEmotionCache,             pageProps } = props;      return (         <CacheProvider value={emotionCache}>             <Head>                 <meta                  	name="viewport"                      content="initial-scale=1,                      width=device-width" />             </Head>             <ThemeProvider theme={theme}>                 {/* CssBaseline kickstart an elegant,                  consistent, and simple baseline to                 build upon. */}                  <CssBaseline />                 <Component {...pageProps} />             </ThemeProvider>         </CacheProvider>     ); }  MyApp.propTypes = {     Component: PropTypes.elementType.isRequired,     emotionCache: PropTypes.object,     pageProps: PropTypes.object.isRequired, }; 

Step 6: Update the Home Component in /pages/index.js with the below code.

JavaScript
// pages/inde.js  import Head from "next/head"; import styles from "../styles/Home.module.css";  export default function Home() {     return (         <div className={styles.container}>             <Head>                 <title>Create Next App</title>                 <link rel="icon" href="/favicon.ico" />             </Head>              <main className={styles.main}>                 <h1 className={styles.title}>                     Welcome to <a href="https://nextjs.org">                         Next.js!</a> integrated with{" "}                     <a href="https://mui.com/">Material-UI!</a>                 </h1>                 <p className={styles.description}>                     Get started by editing{" "}                     <code className={styles.code}>                         pages/index.js</code>                 </p>              </main>         </div>     ); } 

Steps to run the application: To run the app, type the following command in the terminal.

npm run dev

Output:


Next Article
How to use Material-UI with Next.js ?

D

divyanshuparwal2001
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Material-UI
  • Next.js

Similar Reads

    How to use Bootstrap with NextJS?
    Next.js is an open-source web development framework based on React and has gained significant popularity due to its amazing features. It is developed by Vercel and Next.js stands out for its robust capabilities, including server-side rendering(SSR) and enhanced search engine optimization (SEO). Next
    3 min read
    How to Create a Navigation Bar with Material-UI ?
    The Navigation Bar Material UI component provides an efficient way to navigate through web application pages. React utilizes material UI NavBar for responsive and flexible navigation that is easy to implement and also provides animated transitions. ApproachTo create responsive top Navigation Bar Mat
    3 min read
    How to Add Themes in Material UI ?
    In Material UI, themes allow easy customization of design elements like colors and typography in React apps. The MuiThemeProvider component applies these themes across the app, ensuring consistent visuals. Installationnpm install @mui/material @emotion/react @emotion/styledThe table below illustrate
    1 min read
    How to use Box Component in Material UI ?
    The Material UI Box component serves as a wrapper component for most of the CSS utility needs. Material UI for React has this component available for us and it is very easy to integrate. We can use the Box component in ReactJS using the following ways. Prerequisites to use MUI Box ComponentReact JSR
    2 min read
    How to use AppBar Component in Material UI ?
    Using AppBar component in Material UI provides a flexible and customizable navigation bar for your web applications. The App Bar displays information and actions relating to the current screen. Material UI for React has this component available for us and it is very easy to integrate. PrerequisitesR
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences