Spread theme in sx prop MUI 5

Viewed 1104

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.

3 Answers

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.

Using styled() is probably less convoluted.

const Container = styled('div')(theme => theme.mixins.toolbar)

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>
Related