Understanding MUI5 prop handling

Recently, I decided to experiment with Material UI 5 sx props just for fun. I encountered a bit of confusion while trying to replicate the behavior of the previous MUI 4 makeStyles function. Specifically, I was attempting to pass JSS classnames to sx props. In the following code snippet, my goal is to modify the color for even strings:

import { Typography } from "@mui/material";
const styles = {
  green: {
    color: 'green',
  },
  red: {
    color: 'red',
  },
  
}
const options = ['even', 'odd', 'even', 'odd']
export default function CssModulesSlider() {
  console.log('classes', styles)
  return (
    <>
    {options.map((item, index)=> {
      if(index %2 === 0){
        return (
          <Typography sx={{...styles.red}}>
              {item}
          </Typography>
        )
      } else {
       return (
        <Typography sx={{...styles.red, ...styles.green,}}>
            {item}
        </Typography>
       ) 
      }
      
    })}
    </>
  );
}

MUI translates this into different CSS classes:

.css-**1kivl2a**-MuiTypography-root {
//some mui typography stuff here
    color: red;
}
.css-**1ti676r**-MuiTypography-root {
//some mui typography stuff here
    color: green;
}

Everything functions perfectly in this codesandbox example,

However, an issue arises when I alter the order of defining classes within sx props:

//from
sx={{...styles.red, ...styles.green,}}
//to
sx={{...styles.green, ...styles.red,}} 

Although the styles object remains the same as indicated by console.log, MUI now combines them into a single CSS class, causing all list items to have the same class with the color rule set to red. This is not a case of CSS rules being overwritten based on order, as the compiled CSS classes remain identical in both scenarios

While it's recommended to utilize CSS modules, emotion, or styled components instead, does anyone know why this discrepancy occurs?

Answer №1

This isn't exclusive to MUI, but rather a discussion on how the spread (...) operator functions

const styles = {
  purple: {
    color: 'purple',
  },
  yellow: {
    color: 'yellow',
  }, 
}

console.log('...purple + ...yellow => purple', {...styles.purple, ...styles.yellow});
console.log('...yellow + ...purple => yellow', {...styles.yellow, ...styles.purple});

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

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

What is the best way to implement Axios for data fetching in Gatsby's useStaticQuery function?

One way to fetch data in Gatsby is by using GraphQL, like in the following example: import { graphql, useStaticQuery } from "gatsby" const IndexPage = () => { const gatsbyRepoData = useStaticQuery(graphql` { github { repo ...

The ::before pseudo element is malfunctioning when used in the makeStyles function

I am currently utilizing the makeStyles function in React, but I seem to be facing an issue where the content within the ::before pseudo-element is not displaying. Strangely enough, when the content is an image it works fine, but text does not render. Jus ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Mastering the art of handling components in React with a focus on the specialized capabilities of react-sortable-hoc

I'm struggling to grasp a fundamental aspect of this HOC that's gaining popularity on NPM. It seems like there should be a simple solution to my confusion: Where should my existing components be placed in the example provided on NPM? Should {val ...

Differences between React's useCallback and useMemo when handling JSX components

I have created a custom component called CardList: function CardList({ data = [], isLoading = false, ListHeaderComponent, ListEmptyComponent, ...props }) { const keyExtractor = useCallback(({ id }) => id, []); const renderItem = useCallba ...

Selenium encountered an error: Element not found - Could not locate element: {"method":"CSS selector","selector":"*[data-test="email-input"]}

Recently, my application has been encountering an error when trying to log in through a web form. The issue seems to be with locating the email input field: "no such element: Unable to locate element: {"method": "css selector", "s ...

Creating a seamless integration of Material UI V5 ThemeProvider in Storybook V6 within the NX workspace involves a series

I am currently utilizing nx.dev as my monorepo setup with various React clients. With NX, I have centralized the configuration for Material Ui inside the lib folder. The issue arises when I try to integrate Storybook within the mui folder. Unfortunately, ...

Leverage Material UI theme properties to customize the appearance of highcharts in a React application

Recently, I've been implementing Material UI themes for styled components in my React project. However, we now have a new requirement to incorporate highcharts into our application. I want to maintain the same themeing consistency with highcharts as w ...

Is there a way to prevent CSS Module imports in a Next.js component from causing parsing errors during unit testing?

As a beginner in Next.js, I am utilizing CSS Modules in my project and testing with Riteway. However, when I execute unit tests for React components, any component that imports a CSS Module encounters a SyntaxError as it fails to parse the CSS file being i ...

The project is experiencing difficulties in loading the Module CSS

Currently, I am working on a React module and have set up a React project to demonstrate the functionality of this module. Initially, everything was working smoothly until I encountered an issue with the webpack configuration related to the CSS loader. { ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

Is it possible to showcase multiple items in react JS based on logical operators?

How can I update the navigation bar to display different menu options based on the user's login status? When a user is logged in, the "Logout", "Add Product", and "Manage Inventory" options should be shown. If a user is not logged in, only the "Home" ...

Linking an external URL with a button using Material UI - A simple guide

I'm currently exploring Material-UI and testing my web application on localhost. I've added a button that should redirect users to an external URL (currently set as www.google.ca) when clicked. However, instead of redirecting to the correct URL ( ...

Utilizing CSS to Properly Position HTML Elements

Check out my code on jsFiddle I'm facing some challenges in positioning HTML elements using CSS. While I grasp the fundamental concepts of block and inline elements, implementing them in real coding scenarios can be confusing. I've shared my HTM ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

Replicate the functionality of the second parameter of setState within a useState setup, allowing for actions to be taken after the state has been

In the previous version of React, we were able to execute code after the state has changed by using this method: setState( prevState => {myval: !prevState.myval}, () => { console.log("myval is changed now"); ) One way to achieve something simi ...

Unable to preserve the value of react material-ui autoCompletion using formik

Greetings everyone! Today, I wanted to address an issue that has been causing some trouble for me recently. I've been utilizing the autoCompletion feature from materiall-ui along with formik in reactjs. However, I've been facing difficulties when ...

I would like to apply my CSS styles to all the hyperlinks on my website

This is the CSS code I created: img{width:85%; height:auto;} #thumbwrap { position:relative; } .thumb img { border:1px solid #000; margin:3px; float:left; } .thumb span { position:absolute; visibility:hidden; } .thumb:hover, .thu ...

I encountered an error with npm install while attempting to deploy my React website on Netlify

Hi there! I am in need of some assistance. I am encountering an error while trying to host my ready website on Netlify due to an npm install issue. Can anyone guide me on how to resolve this problem? Below are the error comments: 12:28:19 AM: Installing N ...