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

The width of the HTML page seems to adjust or shift when I click on

I'm encountering an issue with my navbar. Whenever I open the dropdown menu, the width of my page changes but returns to normal when it is closed. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="styl ...

Having trouble with Next.js, authLink, httpLink, and GraphQL subscription integration

Struggling to make this work as expected. After some research, I discovered that nextjs/ssr has compatibility issues with subscriptions and it's important to verify the existence of process.browser. However, I am facing challenges in integrating my au ...

What causes the accordion class to activate panels with varying names?

Why are some of my accordions triggering other accordions when they have different names? I've been working on resolving the issue where opening the second accordion in the second, third, or fourth panel closes the second accordion in the first panel ...

conceal elements created with JQuery within an AJAX function

Is it possible to use jQuery and the $.ajax() method to submit a form, displaying only the result while hiding other elements on the page? I am looking to add a conditional in the Ajax method that will show the result if successful, hiding certain elements ...

Is Turbopack compatible with frameworks other than NextJs?

With its impressive speed, it would be great to utilize it in various outdoor projects like Vite. Unfortunately, there does not seem to be much information about it on their website I also checked out https://github.com/vercel/turbo but the details were s ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

I am encountering issues with setting a background image in Bootstrap 3.1.1 while trying to achieve a par

I'm struggling to add a background image to my bootstrap site. I'm attempting to create a parallax site using stellar.js, and while the site is functional with text on each slide and correct scrolling links, the images just won't load. Despi ...

"Is there a way to target an element within another element that has inline styles using

What is the best CSS strategy for targeting elements with inline styles? How can I focus on the first span but exclude the second using only CSS? If that's not achievable, is it possible to accomplish this using jQuery? http://jsfiddle.net/TYCNE/ & ...

Reset the queue for the slideDown animation using jQuery

I am experiencing an issue with my code where multiple animation effects are running simultaneously. Specifically, when I hover over navbarli1 and then move to another li element with the same navbarli1 class, the slide-down effect is not working as expect ...

Unexpected Placement of CSS Grid Items

I am currently facing an issue with aligning items in a nested grid using grid-column/grid-row assignment. After setting the template with grid-template-rows:/grid-template-columns, I expected the $50 and Give Now items to appear on row 3, with one in colu ...

Guide to setting up a node.js server that serves HTML files with CSS styling

I am currently working on setting up a simple node.js server for my HTML using http and express. Everything is functioning properly, but the CSS is not displaying as expected. Here is the code snippet for my server setup: const express = require("express ...

Attempting to divide the main page into quadrants

I want to split my homepage into four equal images without any scrolling. When you click on the website, I want the four images to expand and cover the entire screen with no scrollbars. I've made some progress with my code, but it's not quite the ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

The width of the Div is set to 100%, yet there is still some empty space visible on

I am having trouble setting the background of my code to display a picture that is 300px in height and 100% in width. However, when I set the width to 100%, there are about 15px gaps on each side. I could adjust the width to 1000px, but that presents issue ...

Divs gracefully appear one after the other in a sequential manner

I am attempting to showcase a sequence of 4 divs in a row using the ease-in CSS transition feature. I came across this example that demonstrates what I am aiming for: http://jsfiddle.net/57uGQ/enter code here. However, despite my best efforts, I am unable ...

Getting the first validation message from Input in React: What you need to know

When using a number input with min and max values set, I have found that if a user enters a number above the max value, I can retrieve the validation message from event.target.validationMessage during the onChange event. This functionality works well when ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

What is the process of setting up a proxy for Clerk authentication in a Next.js/Vercel application?

Following the Clerk documentation has been a bit challenging as it seems to lack some crucial information: In my simple Next.js 14 app using the app router pattern and app directory, they mention adding 3 headers to the proxy: Clerk-Proxy-Url: Should con ...