What causes materialui styles to vanish upon refreshing in nextjs?

After consulting the materialui documentation (https://material-ui.com/guides/server-rendering/), I was able to find a solution, but I am still unsure of the underlying reason.

  1. Why does the style work initially during rendering but disappear upon subsequent renderings? According to SSR, the CSS is supposed to be included in the html template delivered to the client with each request, so theoretically, the style should remain.

  2. The documentation mentions that "On the client side, the CSS will be injected a second time before removing the server-side injected CSS." However, it is unclear why this removal process is necessary. The CSS is already injected into the html template for each request, so it shouldn't lead to any crashes in theory. Why, then, does the style vanish once the injected CSS is removed?

Answer №1

If you're using styled-components, simply follow these steps to get started:

Step 1: Install babel-plugin-styled-components as a dev dependency by running npm install --save-dev babel-plugin-styled-components

Step 2: Create a file named .babelrc in the root directory of your Next.js project

Step 3: Add the following code to your .babelrc file:


{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

Step 4: Restart your Next.js server

Answer №2

After making some adjustments to my next.config.js file, everything suddenly started working perfectly. The reasons behind its functionality are a bit fuzzy for me at the moment.

/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    compiler: {
    // https://nextjs.org/docs/advanced-features/compiler
        // For more information on these options, refer to https://styled-components.com/docs/tooling#babel-plugin.
        styledComponents: true,
    },
};

module.exports = nextConfig;

Answer №3

inside _app.js

  function MyApp({ Component, pageProps }) {
  useEffect(() =>{
     const jssStyles = document.querySelector('#jss-server-side');
    if(jssStyles){
      jssStyles.parentElement.removeChild(jssStyles);
    }
  },[]);

  return <Component {...pageProps} />
};

next step is to navigate to _document.js located in the pages folder :

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

export default class MyDocument extends Document{

    render(){

        return(
            <Html lang="en">
                <Head></Head>
                <body>
                    <Main/>
                    <NextScript/>
                </body>
            </Html>
        )
    }
}

MyDocument.getInitialProps = async(ctx) =>{
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;
    ctx.renderPage = () =>{
        return originalRenderPage({
            enhanceApp: ( App ) => ( props ) => sheets.collect(<App { ...props} />)
        })
    };
    const initialProps = await Document.getInitialProps( ctx);
    return{
        ...initialProps,
        styles:[
            ...React.Children.toArray(initialProps.styles),
            sheets.getStyleElement(),
        ]
    }
}

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

What is preventing this code from setting the background color of the main content all the way to the bottom of the

I designed this webpage using HTML and CSS. ... #contents { margin: 0px; padding: 0px; width: 100%; background-color: white; color: black; border-top: 3px solid black; background-image: url(img/CloverImage.png); background ...

Optimizing server layout components with NextJS's on-demand revalidation feature

I recently began developing a new application with NextJS 13 and MongoDB. This app features a dynamic navigation menu whose elements are determined by a configuration object stored in the database. Currently, the navigation menu is integrated into a server ...

Implementing a dynamic top navbar that transitions to the side on desktop with Bootstrap

I have been faced with the challenge of creating a responsive navigation bar that appears at the top on mobile devices and on the side on desktops. The issue arises when considering how to structure the rows and columns to achieve this. For mobile views, ...

Unexpected character appearing in Android 2.3, whether using the li or ul tag

Having an issue with my social icons on the top of my website displaying unwanted symbols in Android 2.3. Can't figure out the cause even after ruling out <a> tags and associated CSS. Any thoughts on what the problem might be? I've remove ...

Is it possible to have 3 divs with the height of the tallest

I have a unique template that I employ for crafting responsive websites. It relies on boxes with percentage widths, floats, and clears. A prime instance can be viewed via this link. Notice how the three boxes vary in height. While it's simple to set a ...

The expected result of getInitialProps() is an object, however it returned "undefined" instead

Currently, I am facing an issue where I am attempting to retrieve data from Firebase in my Next.js application using getInitialProps. However, while the data displays in the VS Code terminal along with some errors, when viewing in the browser, a message ap ...

Discover the steps to develop a dynamic circular progress indicator capable of visualizing data for three distinct values utilizing Mui CircularProgress

Is it possible to display three different values simultaneously in the MUI v5 CircularProgress component? export const StatusCircle: React.FC<Props> = ({ a, b, c }) => { return ( <StyledBox> <StyledCircularProgress size={50} thicknes ...

Every time I rotate my div, its position changes and it never goes back to

Trying to create an eye test by rotating the letter "E" when a directional button is clicked. However, facing an issue where the "E" changes position after the initial click instead of staying in place. Here is a GIF showcasing the problem: https://i.stac ...

Issue with Bootstrap4: organizing columns correctly within and outside a container

I've hit a roadblock while working on a project and can't seem to find the right solution. I've already created a design in Photoshop to illustrate what I'm trying to achieve: Photoshop Design. Basically, I want the main content inside ...

In the realm of typesetting, a punctuated line gracefully weaves its way between two

I am trying to create two sentences with a fixed width of 30%, but the first words in my div go to the next line. The class="left" words are not displaying properly, and then my second div "words" gets mixed with the first div. HTML <div class="bg"> ...

Stop the anchor tag from activating Chrome's status bar

I've been working on a web application with an elastic layout where the footer acts as a toolbar and information display. The footer is always visible at the bottom of the page, without any need for scrolling. We specifically chose this location for t ...

Obtaining hyperlinks to encircle the sound button

Code 1: If you notice, after clicking on the image, the audio button appears and plays without any surrounding links. How can I enable the links around the audio button in Code 1? https://jsfiddle.net/7ux1s23j/29/ <style> .playButton { wid ...

flexbox wrapping text styling

Can text be wrapped in flex within a fixed width container? For example: img username added you as a friend Instead of: user added img name you as a friend I am able to achieve this if the image and 'a' were separat ...

Material-UI - Access all available Menu Items by clicking on the Menu Button

I'm currently facing an issue with Material-UI. Every time I click on a button to open a specific dropdown/menu item, it ends up opening all the dropdown/items in the AppBar. I tried changing the 'open' variable name, but that just resulted ...

Switch up the background image of the <li> element when the <a> tag is clicked

html: <ul> <li id="Co" class="libgc" ><b>CO</b></li> <li id="NSCO" class="libgc active"><span> <a href="#NSale.php" target="homeFrame" class="aclass">NSale</a></span></li> </ul ...

What is the best way to create transparency within an icon's background without affecting the surrounding box?

Is there a way to set the background color of the icon inside the circle without affecting the transparent box around it? Currently, when I use background:white, it changes both the circle and the surrounding box. ...

unable to modify background color when mouse hovers in CSS

Recently, I implemented this code to style the navigation bar on my website. However, I encountered an issue where the color does not change when hovering over the links. .nav { list-style-type:none; margin:0; padding:0; overflow:hidden; } ...

Tips for enhancing the appearance of the dropdown scrollbar in PrimeNG

Just started exploring Angular and I've been struggling to customize the scrollbar on a PrimeNG dropdown. Does anyone have any tips or tricks to achieve this? Here is the HTML code: <p-autoComplete placeholder="- Select -" (onSelect)="onSelect(dh ...

Extending an element beyond the boundaries of its container

I currently have 3 different divisions within the body of my document: a container, a parent, and a child element. My goal is to make the child element extend beyond its parent on the left side. However, when I try to achieve this by using position: ab ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: Here is what I have been able to achieve: In the second picture, the divs are shown separately. My goal is to display the incoming data in a single popup like in the first picture, but I am having trouble a ...