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

Site optimized for mobile devices

I need to create a website that is optimized for mobile devices like Android, iPhone, and Blackberry, as well as desktop and tablet. The screen resolutions of these devices can vary greatly. My supervisor has suggested developing one site that can adjust ...

Utilizing gradient effects on table backgrounds with html/css

Trying to enhance my responsive table by adding a gradient background, but encountering an issue where the style being applied is repeating in every cell, creating a messy look. Here's the gradient I'm using: background: linear-gradient(to right ...

Creating a responsive Google map within a div element: A step-by-step guide

I am experiencing difficulties with implementing a responsive Google map on my webpage. To achieve a mobile-first and responsive design, I am utilizing Google Map API v3 along with Bootstrap 3 CSS. My objective is to obtain user addresses either through th ...

Maintain scrolling at the bottom with React.js

Is there a way to make a div element increase in height through an animation without extending beyond the viewable area, causing the window to automatically scroll down as the div expands? I am looking for a solution that will keep the scroll position lock ...

Error with HTML form validation

After clicking the "Send Request" button, the query string ?req_flag=0 is not appearing in the URL. What could be causing this issue? I want my URL to look like this: localhost/flavourr/send_req.php?req_flag=0&f_e_mail_add=value <pre> <form ...

Numerous calls for the same event

When calling two functions on the same event onChange, I noticed that the second one doesn't execute this.updateValue. As a result, the value of the input doesn't change. However, after removing the first call and changing it to onChange={this.up ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

How to Customize the Navbar Position in Bootstrap 3 when the Brand/Logo is Collapsed

I am currently in the process of creating my first website and experimenting with the Bootstrap 3 framework. The navbar I have selected is designed to adjust based on screen size, collapsing into a small button for use on tablets and mobile devices. Howe ...

The HTML link is not directly attached to the text, specifically in Internet Explorer

When viewing my website in Chrome, the menu links in the Header function correctly. However, in Internet Explorer (specifically version 11), hovering over 'HOME,' 'LISTINGS,' or 'AGENTS' reveals that the displayed URL is incor ...

Certain components in Next.js are not properly reflecting the styles defined in Tailwind CSS

After successfully building a single-page portfolio site on Next using Tailwind, I decided to expand by adding a second page to my project. I created a new file in the pages directory and referenced a new component. While the content is accessible via the ...

The function (0, _hoc.default) is not recognized. Although require cycles are permissible, they may lead to values being uninitialized

Encountered an error when trying to create a HOC using a function component instead of a class component Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle. [Fri Oct 16 2020 24:17:29. ...

Guide on how to align h1 in the navigation bar

I've been attempting to center text on a nav bar but haven't been successful. What could I be overlooking? // include external modules import React, { Component } from "react"; import { Navbar } from "reactstrap"; import { Menu } from " ...

Enhance the appearance of the input range by styling it with an additional class both before and

I have a JSF page where I am using an input range element. I want to add a different style class before and after the input range. Specifically, I want to display a plus icon (ui-icon-plusthick) before the input and a minus icon (ui-icon-minus) after the i ...

Customize the MUI Slider Component with unique colored thumbs

Check out MUI's slider component at this link. I'm using it to let users select a value range with two thumbs. You can find the documentation for MUI's multi-thumb slider here. If you want to customize the style of the slider thumb, visit ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

Looking for ways to incorporate both external and internal styling using jQuery and CSS in my template?

I've been working on a django project for a while now, and I'm facing some challenges with getting external and internal CSS to work. Only inline CSS seems to be functioning properly. I have two questions: How can I get external or internal C ...

react scroll event not displaying drop shadow

As a newcomer to JavaScript React, I've been attempting to create a feature where the navbar drops a shadow when the user scrolls down. Unfortunately, it's not working as intended. Can anyone point out what I might have done incorrectly? I suspe ...