Why doesn't the style show up when JavaScript is turned off with Material UI, CSS Modules, and Next.js?

This is my first time diving into Material UI, CSS Modules, and Next.js with a project.

Issue:
I noticed that when I disable JavaScript in the Chrome DevTools, the styles are not being applied. I'm not sure if this has something to do with Material UI or maybe how I am importing the styles?

I've been searching for an answer but haven't found anything yet. Any assistance would be greatly appreciated. Thank you so much!!

Below is some relevant code snippet:

//pages/_document.js
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';
import theme from './_theme';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <meta name="theme-color" content={theme.palette.primary.main} />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;

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

  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
  };
};



//pages/_app.js
import React from "react";
import "../styles/global.css";
import { ThemeProvider } from "@material-ui/core/styles";
import theme from "./_theme";
import CssBaseline from "@material-ui/core/CssBaseline";

function MyApp({ Component, pageProps }) { 
  React.useEffect(() => {
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);
  
  return (
    <>
      <ThemeProvider theme={theme}>
        <CssBaseline>
              <Component {...pageProps} />
        </CssBaseline>
      </ThemeProvider>
    </>
  );
}

export default MyApp;



//componentXYZ.js -> Importing styles example
import Input from "@material-ui/core/Input"; //from material ui
import styles from "./componentXYZ.module.css //other styles

Answer №1

Your code is not the issue at hand

According to the documentation for Next.js :

"Even if JavaScript is disabled, CSS will still load in the production build (next start). However, during development, enabling JavaScript is necessary for a better developer experience with Fast Refresh."

Refer to the documentation for more details

Answer №2

To properly view CSS while using a local Next.js development server, JavaScript is necessary.

After the server side rendering process is complete upon building, JavaScript becomes unnecessary in production for the initial render with styles applied. Next servers will deliver all HTML and CSS as pre-rendered static files.

Check out their demo site at

With JavaScript Enabled: https://i.stack.imgur.com/64b3u.png

With JavaScript Disabled: https://i.stack.imgur.com/fCTHw.png

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

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

Leveraging the ng-hide property of one controller to adjust the ng-style attribute of another controller through a centralized global controller

Seeking assistance with accessing the boolean value of ng-hide from one controller in order to alter CSS properties of another controller utilizing a global controller. Here is the jsfiddle link: https://jsfiddle.net/dqmtLxnt/ HTML <div ng-controller= ...

Issue with React-Native FlatList's scrolling functionality

Struggling with implementing a scrolling FlatList in React Native. Despite trying various solutions found on Stack Overflow, such as adjusting flex properties and wrapping elements in views, the list still refuses to scroll. Snippet of code (issue is with ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

I'm having trouble customizing the appearance of a Tab Panel using the TabsAPI. The panel keeps expanding in strange ways. How can I

Trying to customize the Tabs component from MUI is proving to be a challenge. The main issue I am facing currently is: Whenever I switch between tabs, they appear to expand in size mysteriously. This behavior seems to occur only on tabs with more content ...

Adding elements to a two-dimensional array using AngularJS

How can I assign the value of an input to tasks.name and automatically set status: false when adding a new item to the $scope.tasks array? HTML <input type="text" ng-model="typeTask"> <button ng-click="updateTasks()">Add task</button> ...

Is there any difference in loading speed when using an async function in the createConnection method of promise-mysql?

Is it more efficient to use asynchronous createConnection or not? Does this impact the loading speed in any way? I am working with express, ReactJS, and promise-mysql. Which approach is preferable? Option 1: async connect () { try{ ...

Experience the sleek design of React material-ui's AvatarGroup with a rounded shape that allows

Is it possible to customize the shape of an additional item appended to a React Material-UI AvatarGroup when the number of Avatars exceeds the specified maximum, so that it aligns with the rounded variant of the Avatars? https://i.stack.imgur.com/kUmsp.pn ...

What could be the reason for the ReferenceError that is being thrown in this code, indicating that '

let number = 1; console.log(number); Feel free to execute this basic code snippet. You may encounter an issue: ReferenceError: test is not defined, even though the variable was declared. What could be causing this unexpected behavior? ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

When using the Google Maps API fetch() method, the response is empty. However, when accessing the same

I am currently working on extracting the "photo_reference" from the JSON data provided below; { "html_attributions" : [], "results" : [ { "formatted_address" : "Bandar Seri Begawan, Brunei", "geometry" : { "locati ...

What's the method for positioning the footer at the bottom of the grid without impacting the layout of the other rows?

I am trying to achieve the placement of the footer at the bottom of the layout page when the height is shorter than the window. While it is often suggested to use min-height:100vh, this approach ends up increasing the height of other elements as well. I am ...

Adding a border with vertical padding above and below two floated divs with different heights

Here is some sample markup: <div class="container"> <div class="one">column a<br />column a</div> <div class="two">column b</div> </div> The content in the inner divs can vary in height and is dynamically g ...

Striking a line through the hyperlink tag

I am attempting to create a crossed-out line above the content of an a tag for decorative purposes. The line should stretch across the entire width without intersecting with the actual text within the tag. This is my desired outcome: This is my current p ...

Unable to change Bootstrap variables within a Next.js project

I'm having trouble changing the primary color in Bootstrap within my NextJS project. I've tried different methods but nothing seems to work as expected. Here is the code snippet from my "globals.scss" file that I imported in "_app.js": $primary: ...

javascript issue with showing content on click

I'm currently working on a school assignment where I am using the onclick() function to display information about an object. However, I am facing an issue where the information is not popping up as expected. HTML <!DOCTYPE html> <html> ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...