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?