'Spread theme in sx prop MUI 5
The previous code, which used v4, was
const useStyles = makeStyles(theme => ({
toolbarMargin: {
...theme.mixins.toolbar
}
}))
How to migrate this code to MUI v5 using sx prop, I tried using it like this
<Box
sx={{
...(theme) => theme.mixins.toolbar,
}}
/>
but the theme was not defined.
Solution 1:[1]
You can do the following:
<Box sx={theme => theme.mixins.toolbar} />
or
<Box sx={theme => ({
...theme.mixins.toolbar,
// other sx stuff
})} />
As you can also pass a function with theme as parameter to the sx prop, it must return valid sx object.
Solution 2:[2]
For me most of the solutions above resulted in an non fatal error, as sx accepts object, not functions. This worked:
<Box
sx={{
"&": (theme) => theme["whateverYouWishToSpread"]
}}
>{someStuff}</Box>
Solution 3:[3]
Using styled() is probably less convoluted.
const Container = styled('div')(theme => theme.mixins.toolbar)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ernestkosma |
| Solution 3 | El Yobo |
