Problem with the latest MUIv5 and classes/withStyles overrides of nested elements
See original GitHub issueHello,
when I created this PR https://github.com/garronej/tss-react/pull/54 we were still using MUIv4. We are using overrides with classes
prop and withStyles
of MUI components a lot and since we started migrating to MUIv5, I’ve noticed something strange.
I’ve create a demo here:
- deployed example site: https://muiv5-problem-with-classes.vercel.app/
- related code: https://github.com/synaptiko/muiv5-problem-with-classes/blob/master/src/App.tsx
I followed the recommended steps from both tss-react
and MUI projects to eliminate issues with the setup.
The problem in a nutshell is the following, when you have a component with sub-elements and you’d like to override default styles (let’s say color or background color), one would expect to use what was possible in MUIv4:
const StyledChip = withStyles(Chip, (theme) => ({
root: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
},
deleteIcon: {
color: theme.palette.primary.contrastText,
'&:hover': {
color: `${theme.palette.primary.contrastText}6`,
},
},
}));
But it doesn’t work because of CSS selector specificity:
The only solution I found is with:
const StyledChip = withStyles(Chip, (theme, _props, classes) => ({
root: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
[`& .${classes.deleteIcon}`]: {
color: theme.palette.primary.contrastText,
'&:hover': {
color: `${theme.palette.primary.contrastText}6`,
},
},
},
}));
Unfortunately it requires a lot of refactoring in our code and it’s also quite hard to reason about, you need to know that you are fighting with specificity here (which I assumed that emotion
-based solution should help to avoid).
I’m not 100% sure if it’s a problem in tss-react
itself or if it’s more about how MUIv5 handles classes
props.
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (8 by maintainers)
Top GitHub Comments
Got it, I understand it’s not an easy job to support customization, especially with more than one CSS engine. In any case, thanks for you help, feel free to close this issue and let’s see if someone from MUI can help or if we just need to refactor the code to increase specificity.
OK, thank you for the extra details.
I was making sure there wasn’t anything I can do for you and I am afraid this is effectively the case.
In defense of the MUI team, if they are facing all theses specificity issues it is because they are allowing users to use
styled-component
instead of@emotion
as underlying style engine. ref. It makes their job 10 times harder, I am not sure it’s worth it.