Search code examples
reactjsmaterial-uigatsbystyled-components

Select component losing it's css when page is refreshed


I'm building a small website for my company's break room written in React and using Gatsby to translate the app into static content.

I've found that when I refresh the page where my Menu is, the Select elements from Material-UI lose their CSS.
Nothing else in the page loses it's styling, including the MenuItem components from Material-UI that I'm using to populate the Select component with options.

I am using styled-components to customize the size/position/feel of the Select components, and I've tried removing the styling to see if that was the issue but it didn't affect the behavior.
If 1- I login to the website and 2- navigate to the Menu page the CSS renders properly, but if refresh the page it breaks the Select component, causing it to lose it's CSS.
+ Also, if I browse directly to the page it breaks the Select component's CSS.

I also noticed some errors in Firefox, when the page is refreshed saying that it was ignoring rulesets due to bad selectors. Errors can be seen at the link below.

Select component Styled:

const StyledSelect = styled(Select)`
width: 80%;
margin-right: 10%;
margin-left: 10%;
margin-top: 3%;
margin-bottom: 3%;`

Select component used in render():

<StyledSelect
 multiple={props.isMultiple}
 value={props.value}
 name={props.name}
 onChange={props.handleChange}
>
 {props.items.map(item => (
  <MenuItem key={item._id} value={item}>
   {item.Name}
  </MenuItem>
 ))}
</StyledSelect>

I expect the CSS to be persistent even when the page is refreshed, but the actual result is that the Select component breaks after the page is refreshed.

Gif of Issue: https://i.sstatic.net/0ORuP.jpg
Picture of Firefox CSS Warnings: https://i.sstatic.net/3SjRB.jpg


Solution

  • You have a problem with SSR, when you reload the page what happen is it gets only the style injected correctly, apparently what you did is install material-ui and expect it to work, what you should do is inject material-ui's style, apparently that needs some configuration with react-jss, lately material-ui and because of such like issues that everyone complain about they provided examples on how you can solve this issue, one of those examples is gatsby project https://github.com/mui-org/material-ui/tree/master/examples/gatsby , if you do not have time for that you can just install a gatsby plugin https://www.gatsbyjs.org/packages/gatsby-plugin-material-ui/ and you won't have this issue again.