I am wondering if there is a neat trick to use a component classes
prop to override some CSS defined in a theme's overrides.
For instance :
If I want all Button
components to have a different font-size
than the default one. I can use the theme.overrides props to do so :
// this works, all Buttons text is 1.1rem
let theme = createMuiTheme({
overrides: {
MuiButton: {
label: {
"&": {fontSize: "1.1rem"}
}
}
}
})
Now if for some reason one of my button needs to have a different font-size
, I was hoping using classes prop would do the job :
const useClasses = makeStyles({
smallerFontSize: {
fontSize: "0.9rem"
}
})
...
const classes = useClasses()
...
<Button
classes={{
// unfortunately this doesn't work, theme overrides is taking precedence
label: classes.smallerFontSize
}}
>
Some smaller text
</Button>
...
Since using classes
prop allows us to target and override some component's CSS if default theme values have not been overridden, I find it confusing that theme overrides end up behaving somewhat differently and have a higher specificity than a one time rule.
I'd argue it kind of defeats the purpose of having a customisable theme.
But hopefully I'm missing something and your wisdom will help !
UPDATE
My mistake was to export the created theme and the makeStyles hook from the same module file.
Doing that made Mui insert theme <style>
after the hook <style>
.
To fix the issue and be able to use classes component props as I wanted to :
- export theme and hooks from separate modules
- make sure theme module has no dependency on the module exporting the hook
- make sure when using
ThemeProvider
that it has no parent component importing the hook
I still don't quite understand why things worked before I added the overrides property on the theme object though.