Production Challenges: Addressing Style Problems with Material UI and Next JS 13

  • Using MUI in DEV results in a custom design for my application
  • In Prod, the custom design is missing when using MUI

Do I need to implement something differently? Is there an extra configuration required?

An example of something not working:

       <Typography className={styles.customStyle} component="h1">
          {t("Translation")}
        </Typography> 

The className={styles.customStyle} is being ignored completely in Prod, although it works fine in DEV.


Details of my current configuration

  • Node version: v19.0.0

  • Package.json details:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    // Additional dependencies listed here
  }
}

  • Additional configurations in next.config.js:
/** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: true,
  experimental: {
    appDir: true,
  },
}

module.exports = nextConfig

Answer №1

UPDATED:

After going through the content on this website: https://blog.logrocket.com/getting-started-with-mui-and-next-js/

I noticed that a crucial element was missing, which is the addition of <CacheProvider />. By adding this, the custom styling started working correctly.

RESOLUTION:

To solve this issue, begin by creating a new file named createEmotionCache.js in the utils directory.

import createCache from "@emotion/cache";

export default function createEmotionCache() {
 return createCache({ key: "css", prepend: true });
}

Next, navigate to either _app.js or page.js (if using LAYOUT RFC)

....
import { CacheProvider } from "@emotion/react";

const clientSideEmotionCache = createEmotionCache();

function MyApp({
 Component,
 emotionCache = clientSideEmotionCache,
 pageProps,
}) {
 return (
   <CacheProvider value={emotionCache}>
     <App />
   </CacheProvider>
 );
}

export default MyApp;

That's it for now.

Answer №2

While your solution may appear to work, it lacks effectiveness in terms of performance optimization. Upon testing in Chrome for performance, it was observed to be slower than an alternative method by approximately 1 second due to the need for re-calling CSS.

The image below illustrates the FCP after 0.5 seconds: https://i.sstatic.net/slsYd.png

However, adopting your suggested solution would result in a delay of 1.5 seconds in my specific scenario (and generally slower in all cases). You are encouraged to utilize the StyledEngineProvider as outlined in the MUI documentation at https://mui.com/material-ui/guides/interoperability/#css-injection-order-3. This approach has proven effective in enhancing performance in my experience. Give it a try!

import * as React from 'react';
import { StyledEngineProvider } from '@mui/material/styles';

export default function App() {
  return (
    <StyledEngineProvider injectFirst>
      {/* Your component tree. Now you can override Material UI's styles. */}
    </StyledEngineProvider>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring information to a different component

I am trying to figure out if there is a way to pass data directly from a row in my MUI Table to another page using useNavigate instead of relying on localStorage. Any suggestions? <TableBody> {data && ...

Sending input data without a form

Currently, I am in the process of developing a website game and facing a challenge with implementing a feature I refer to as "dialogue". Initially, I attempted to address this issue by using a form element, but encountered a problem where pressing enter o ...

Preventing memory leaks by harnessing the power of Node Streams and promises

I am trying to wrap node streams in an async function, but I'm concerned about potential memory leaks in the following code. Will readStream and result be properly garbage collected after the promise is resolved or rejected? If not, what steps can I t ...

Textbox with Placeholder Text and Entered Data

When working with an HTML input box to enter a value that will be used to run a PHP script, it is possible to pass that value using the URL and GET method. To enhance user experience, I wanted to add a watermark hint in my textbox. After some research, I ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Styling elements using the nth-child selector in JavaScript

I am trying to apply a CSS class based on the combined height of the 2nd and 3rd child elements. For example, if the height of the 2nd child plus the height of the 3rd child equals a certain value, I want to add a specific class. Here is my JavaScript cod ...

Utilizing Http to Retrieve JSON Data in Ionic 3

Struggling with Ionic, trying to fetch data from a JSON File using HTTP, but encountering a strange error. https://i.sstatic.net/L2nVo.png Below are the relevant code snippets : src/pages/subhome/line/line.ts (The Subhome consists of multiple nested pag ...

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

The icon is being displayed as text instead of the actual Fontawesome icon

Using jquery version 3.3.1 I am dynamically creating an anchor tag: let link = $("<a>"); link.attr("href", "#"); link.text("My anchor" + ' <i class="fas fa-people-carry"></i>'); However, when I try to display ...

How to Add Data from Another MongoDB Collection in Mongo/Meteor

I am looking to incorporate a document from one collection into another, specifically a UoM into Products. Template.NewProduct.helpers({ ... uoms: function() { return UoM.find(); }, ... }); Template.NewProduct.events({ //Submit and Add to ...

Material UI categorizing iPads with a width of 768px and a height of 1024px as belonging to the small

I am facing a challenge with the layout of my app on different screen sizes. To address this issue, I am utilizing Material UI's breakpoints to control the layout based on the screen size. According to the documentation, screens categorized as small ...

Guide: Writing code that caters to different types of media in React using Material-UI

After reviewing the documentation, I believed that the optimal solution in later versions of material-ui was to use useMediaQuery, but unfortunately, I am unable to implement it correctly. My objective is to hide a menu when the page is being printed, so I ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

Sending data from one Angular component to another on a button click

I have a background in Python, but I recently started delving into learning Angular and I'm encountering some difficulties. The concept of working between components is proving to be quite confusing for me, and I'm struggling to grasp it. Despite ...

Issue with Vuex causing error message "TypeError: Unable to access property 'getters' of an undefined object"

I am facing an issue where Vuex seems unable to locate my getter for the loading_state. While the vuex state and getter are visible in the Vue developer tools, I am unable to access them within my application. I have attempted to make changes such as mod ...

The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected. //Html <div id="mainapp"> <span class="star" v-bind:class="{ ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Refresh element once AJAX call is completed successfully

Issue Despite a successful AJAX request, I am encountering difficulties updating an element on the webpage. JavaScript Code $(function() { $(".upvote").click(function() { var id = $(this).parent().find("input").val(); $.ajax( ...

What could be causing the 404 Ajax not found error in my script?

I'm facing an issue with my code. When I try to run it, I encounter the following error: 404 (Not Found) while using the get method. Here is my html code snippet. <html> <head> <title>Issue</title> <meta charset= ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...