CSS disruptions occur during the deployment of Gatsby with MaterialUI components

I have a Gatsby site with MaterialUI Components, but I'm facing an issue with CSS styles being applied to the wrong components. The root of the problem seems to lie in the following code snippets:

Layout.js


    <ThemeProvider theme={theme}>
      <CssBaseline/>
      <Header onMenu={() => setMenuOpen(true)}/>
      {children}
    </ThemeProvider

Header.js


const NavigationBar = ({onMenu}) => {
  const trigger = useScrollTrigger({target: (typeof window !== `undefined` ? window : undefined)})
  const data = useStaticQuery(query)
  return (
    <React.Fragment>
      <Slide appear={false} direction="down" in={!trigger}>
        <AppBar color={"primary"}>
          <Toolbar disableGutters={true}>
           ...
            <LaptopAndWider>
              {data.dataJson.navigationPrimary.map(x =>
                <Button key={x.title} component={Link} to={x.path} color="inherit" underline={"none"}>
                  <Box height="70" alignItems="center" justifyContent="center" display="flex"> // This styles (height, flexBox) gets applied to the wrong item
                    <Typography variant={"h6"}>
                      {x.title}
                    </Typography>
                  </Box>
                </Button>
              )}
              {data.dataJson.navigationSecondary.map(x =>
                <Button key={x.title} component={Link} to={x.path} color="inherit" underline={"none"}>
                  <Box height="70px" alignItems="center" justifyContent="center" display="flex">
                    <Typography variant={"body1"}>
                      {x.title}
                    </Typography>
                  </Box>
                </Button>
              )}
            </LaptopAndWider>
           ...
          </Toolbar>
        </AppBar>
      </Slide>
      <Box height={82}/>
    </React.Fragment>
  );
}

Index.js


const IndexPage = ({data}) => (
  <React.Fragment>
    <Box>
      <GatsbyImage fluid={data.file.childImageSharp.fluid}
                   />
    </Box>
    ...
  </React.Fragment>
)

My Gatsby plugins may be causing this issue:


  plugins: [
    ...
    `gatsby-theme-material-ui`,
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-plugin-layout`,
      options: {
        component: require.resolve(`./src/components/Layout`),
      },
    }
  ],

While CSS works fine in development with 'gatsby develop', it breaks in production ('gatsby build' & 'gatsby serve'). The CSS meant for navigation bar items is applied to the Box surrounding my image, creating a messy look on the site.

I've tried various solutions such as removing 'gatsby-plugin-offline', reordering components, eliminating 'gatsby-plugin-emotion', cleaning caches, updating packages, and more, but the issue persists. It has been a source of frustration, especially in the production environment.

For a better understanding of the problem, you can check out a sample on GitHub: https://github.com/Console32/BrokenCss

Answer ā„–1

The issue is originating from the LaptopAndWider component. This particular component utilizes MediaQuery from react-responsive for the purpose of hiding elements on various screen sizes. Due to this setup, the server-side rendering (SSR) did not render the Material UI Components located beneath LaptopAndWider, resulting in a lack of proper styling. On the other hand, client-side rendering (CSR) worked as expected. This explains why the correct styles were applied after navigating back and forth within the application.

To rectify this issue, the solution lies in replacing the MediaQuery from react-responsive with Hidden from @material-ui/core.

            <Hidden mdDown>
              {data.dataJson.navigationPrimary.map(x =>
                <Button key={x.title} component={Link} to={x.path} color="inherit" underline={"none"}>
                  <Box height="70" alignItems="center" justifyContent="center" display="flex"> // These styles (height, flexBox) are being applied to the incorrect element
                    <Typography variant={"h6"}>
                      {x.title}
                    </Typography>
                  </Box>
                </Button>
              )}
              {data.dataJson.navigationSecondary.map(x =>
                <Button key={x.title} component={Link} to={x.path} color="inherit" underline={"none"}>
                  <Box height="70px" alignItems="center" justifyContent="center" display="flex">
                    <Typography variant={"body1"}>
                      {x.title}
                    </Typography>
                  </Box>
                </Button>
              )}
            </Hidden>

Answer ā„–2

The issue of conflicting CSS classnames arises when utilizing a multitree setup within your application.

To overcome this conflict, you can implement a classname generator to create the classes. This will ensure that both Gatsby and MDX use the same generator for generating classnames.

First, install the react-jss package:

yarn add react-jss

Next, in your src/components/Layout.js file, include the following code to use the same classname generator:

import React from 'react';
//...
import {createGenerateId, JssProvider} from 'react-jss';

const generateId = createGenerateId();

const Layout = ({children}) => {  
  //...
  return ( 
    <JssProvider generateId={generateId}>
      <ThemeProvider theme={theme}>
      {/* ... */}
      </ThemeProvider>
    </JssProvider>
  );
}

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

Identifying sluggish hardware or unresponsive browsers using JavaScript

My site features numerous CSS animations and transitions that run very slowly on specific browsers and older hardware. I want to avoid user-agent sniffing; is there a way to identify browsers or hardware configurations using JavaScript or a JS library, and ...

The functionality of Nativescript squared buttons is not functioning as expected

I recently developed a Nativescript app using Angular, incorporating customized buttons. However, I have encountered an issue where I am unable to achieve perfectly squared buttons with the desired appearance. Here is my CSS code: Button { font-size: ...

Resetting a component's color to its default state after being styled by a parent selector

The Bootstrap stylesheet contains the following code: pre code { color: inherit; } Even if I include an explicit pre code { color: red; }, the style from Bootstrap's stylesheet still takes priority. Why does this happen? [Edit: can ignore this ...

image in the background following the header

Live Example: http://jsbin.com/opokev/54 I am currently trying to set this image as the background image while also including a header, but as you can see in the demo, the header is overlapping the image. Is there a way I can rearrange this so that the h ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Issue with the height of Bootstrap 4 navigation bar

After deciding to use Bootstrap 4 for my current project, I encountered an issue with the navbar. It seems to expand too much, which is only happening once I deploy the website. Can anyone help me figure out what's causing this problem? Below is the c ...

Creating a visually appealing webpage by utilizing Bootstrap and HTML for the layout

I am in the process of learning html and Bootstrap for CSS. Below is the code I currently have: <div class="container"> <div class="row text-center mb-4 mt-2"> <div class="col-md-12"> <div cla ...

What causes discrepancies in CSS design across different browsers?

I have implemented the following CSS and HTML code to display an L shape before a span, but its appearance differs across different browsers. In Mozilla Firefox https://i.sstatic.net/1rCoJ.png and In Safari https://i.sstatic.net/YKiJ7.png .bulletInli ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

jss-rtl does not invert styles, meaning it does not reverse rules along the x-axis

I am currently working on a test application that utilizes Material UI with RTL enabled. I have set a margin left for my button in the application, but despite using jss-rtl, the margin does not switch to margin-right as expected - it remains as margin-lef ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

Creating an opaque effect on a Material UI Drop down menu: Step-by-step guide

For the last half hour, I've been experimenting with my Select dropdown menu in an attempt to make it semi-transparent, but without success. I've tried adjusting the properties of the Paper, then the Menu, and then the MenuList, yet it appears th ...

"Exploring the versatility of using variables in jquery's .css

Iā€™m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

Struggling to align navigation items in the center while maintaining responsiveness with CSS and Bootstrap

I am trying to achieve a responsive centering of my navbar-brand across all platforms, while also positioning my nav items and links, including the navbar-toggler, on the right side. Currently, on larger screens, it appears as shown in this image: here. Ho ...

Utilizing JavaScript to assign a CSS class to an <li> list item

I am working on a page that includes a menu feature: https://jsfiddle.net/dva4zo8t/ When a menu button is clicked, the color changes and I need to retain this color even after the page is reloaded: $('[id*="button"]').click(function() { $( ...

Increasing the height of a DIV that is positioned beneath another DIV with a set height

My goal is to convey my message visually. I hope you can understand without too many words. The issue I am facing is that when trying to stretch a 100% height DIV under another DIV with fixed height, it does not stretch properly. If you want to experiment ...

The absence of ellipses in Typography MUI is a glaring omission

I'm looking to truncate long text with an ellipsis, but it doesn't seem to be working. Is there something wrong with my code or how can we improve it? CODESANDBOX -----> CLICK HERE <Typography variant="body2" color="blac ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

Is there a way to ensure that all elements on a page display properly across all screen resolutions without being cut off?

My website consists of three main elements: pictures, Cards (containing pictures and various typography), and Buttons. These elements are arranged in a column layout. The issue I am facing is that the pictures and buttons get cut off on the screen due to ...

What is the best way to showcase initial values in a material-ui autocomplete field?

I am utilizing the autocomplete feature from material-ui (v5) along with formik for creating forms in my project. Within this form, I have several lists that are defined as constants. To populate these lists with default values, I make use of an API which ...