Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png

If you are facing the error/missing CSS, check out this video for a visual representation.

While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not match, finding a clear solution specific to your stack can be challenging.

My current tech stack includes:

  • Node JS
  • Next JS
  • Material UI

Based on insights from posts like next.js & material-ui - getting them to work, it seems there might be compatibility issues between Next JS and Material UI.

Concerning my code, here is an excerpt from my Appbar component. Initially, I wasn't exporting the useStyles object, but later attempted to do so based on references like Material UI's guide to "server rendering". Is there a fix that doesn't involve making changes across all files?

import React from 'react';
// More code...
export {SearchAppBar, useStyles};

Answer №1

While aimlessly searching the depths of the internet for solutions to a perplexing error, I mistakenly executed a npm install command on styled-components due to a reference in this response on a Github issue. This mishap occurred as they presented an object similar to Material UI's ServerStyleSheet (as opposed to Material UI's

ServerStyleSheets</code), which obviously did not yield any positive results.</p>

<p><strong>BUT.........</strong> In a twist of events, I decided to implement the <code>ServerStyleSheet
workaround to align it with Material UI's ServerStyleSheets object, resulting in the creation of a new _document.js.

I am still astonished at how I managed to adapt a completely different solution to resolve the issue successfully. After testing it, I can confirm that the problem has been fully rectified and page reloads function seamlessly.

import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from "@material-ui/styles";

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheets();
        const originalRenderPage = ctx.renderPage;

        try{
            ctx.renderPage = () => originalRenderPage({
                enhanceApp: App => props => sheet.collect(<App {...props}/>)
            });

            const initialProps = await Document.getInitialProps(ctx);
            return { ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            ctx.renderPage(sheet)
        }

    }
    render() {
        return (
            <Html>
                <Head>
                    <link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
                    <style>{`body { margin: 0 } /* custom! */`}</style>
                    <meta name="viewport"content="width=device-width, initial-scale=1.0" />
                </Head>
                <body className="custom_class">
                    <Main />
                    <NextScript />
                </body>
            </Html>
    )}
}

export default MyDocument;

If you want to witness the uncanny success story behind this fix, here is an alternative solution for the same error using styled-components:

export default MyDocument;

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const sheet = new ServerStyleSheet()
        const originalRenderPage = ctx.renderPage

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
                })

            const initialProps = await Document.getInitialProps(ctx)
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            sheet.seal()
        }
    }
}

I hope this account of my experience helps others navigate through the complexities of Material-UI + Next.js integration.

Answer №2

After doing some research, I stumbled upon a solution that seems to work for me - adding

{ name: "MuiExample_Component" }
in the makeStyle hook. I'm not entirely sure if this is the best approach, so I would really appreciate any feedback on whether this is a good solution or not. Below is the code snippet:

const useStyles = makeStyles({
    card: {
        backgroundColor: "#f7f7f7",
        width: "33%",
    },
    title: {
        color: "#0ab5db",
        fontWeight: "bold",
    },
    description: {
        fontSize: "1em"
    }
}, { name: "MuiExample_Component" });

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

Navigating data in a Json array object

Can someone assist me in retrieving data from a JSON array file stored at the following link? Html <div> <div v-for="data in myJson.id " >{{ data }}</div> </div> js import json from '.././json/data.json&apo ...

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

Why is the value of the select element in AngularJS an object?

Here is a JSON object: { "9000A": { "LOCname":"A Place", "LOCid":"9000A" }, "2700C": { "LOCname":"C Place", "LOCid":"2700C" }, "7600B": { "LOCname":"B Place", "LOCid":"7600B" } } To ...

The proper way to update MUI styles

click here to see an image I am looking to customize the background style in this code snippet: MuiAccordion: { styleOverrides: { root: { boxShadow: 'none', position: 'inherit', '& .Mui-expanded': ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

Is it possible for image.src to pose a security threat?

Here is the code snippet I am working with: var image = new Image(); image.src = "https://MyTrackingSite.com/?myTrackingParameter=whatever" I noticed that the image is not added to the DOM tree. Is it still rendered by the command "image.src"? Could this ...

Error in sending Ajax form

I have a form that is set up to send data to a server. When the form is in its regular HTML format, everything works smoothly and all data is successfully transmitted to the server without any issues. However, as soon as I switch the form to use AJAX for s ...

sending back a JSON object that appears empty, despite actually containing data

I'm facing an issue where I am attempting to send a json response to my react client, containing a list of songs (objects). However, the json returns as an empty array. This is how I am fetching the data: let songs = []; fetch("https://api.spotify. ...

Tips for eliminating double quotes from an input string

I am currently developing an input for a website that will generate a div tag along with its necessary child elements to ensure the website functions correctly. I have a couple of key questions regarding this setup: <!DOCTYPE html> <html> < ...

Tips for stretching the background image to full width

I am trying to set the background to be full width like the image below (must be responsive). However, when I applied it, the result looks like this and crops the bottom part. Can someone please assist me with this issue? ...

i18next fails to update the language in a Next.js application

Utilizing i18next for localization has been quite successful in translating English text to Arabic {t("title")} ==> مرحبا. However, I'm facing an issue when attempting to switch the language back to English using the following code: ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...

The search bar in MuiDataTable does not dynamically update a column containing custom components

Greetings! I'm currently exploring the world of nextJs and react, so my understanding is quite limited :). One issue I am facing involves a MUIDataTable with dropdown columns. When using the search bar, the dropdown value doesn't update and rema ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...

Creating a three-column layout in HTML5 with resizable left and center columns, and a fixed right column

Looking to create a full screen layout with three columns, where the left/center column is resizable and the right column remains fixed. Currently using the resize style for the left area, but running into issues as the center area does not adjust in size ...

The server's delayed response caused the jQuery ajax request to be aborted

Encountering delayed AJAX response from the PHP server upon aborting the AJAX request. Currently utilizing the CodeIgniter framework for the server script. Javascript Code: cblcurrentRequest = $.ajax({ url: baseurl + 'Login/getChannelBra ...