Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access theme within a breakpoint attribute in MUI 5?

I need to use my theme.spacing in my sm breakpoints, but no attempt is working.

sx={{
  paddingTop: { sm: 0 },
  paddingRight: { sm: "spacing(6)" },
  paddingBottom: { sm: "spacing(10)" },
  paddingLeft: { sm: "theme.spacing(6)" },
  "@media screen and (orientation:landscape)": {
    paddingTop: { sm: 0 },
    paddingRight: { sm: "spacing(6)" },
    paddingBottom: { sm: "spacing(2)" },
    paddingLeft: { sm: "theme.spacing(6)" },
  },
}}

or this

sx={{
  paddingTop: { sm: 0 },
  paddingRight: { sm: (theme) =>  theme.spacing(6) },
  paddingBottom: { sm: (theme) =>  theme.spacing(10) },
  paddingLeft: { sm: (theme) =>  theme.spacing(6) },
  "@media screen and (orientation:landscape)": {
    paddingTop: { sm: 0 },
    paddingRight: { sm: (theme) =>  theme.spacing(6) },
    paddingBottom: { sm: (theme) =>  theme.spacing(2) },
    paddingLeft: { sm: (theme) =>  theme.spacing(6) },
  },
}}

How can I use theme values with breakpoint (sm, md, lg, etc)

like image 396
bonum_cete Avatar asked Sep 14 '25 07:09

bonum_cete


1 Answers

Many of the sx properties are theme aware including the padding so you don't need to use the theme callback to get the theme value:

sx={{
  paddingRight: {
    xs: 0, // theme.spacing(0)
    sm: 3, // theme.spacing(3)
    md: 5, // theme.spacing(5)
  },
}

But for some reasons if you want to use callback (for example to calculate with other values), this is how you can do it:

Normal value
paddingRight: 2,
Normal value with callback
paddingRight: theme => `calc(${theme.spacing(2)} * 10)`,
Breakpoint value
paddingRight: {
  xs: `calc(0px * 10)`,
  sm: `calc(4px * 10)`,
  md: `calc(8px * 10)`,
},
Breakpoint value with callback
paddingRight: (theme) => ({
  xs: `calc(${theme.spacing(0)} * 10)`,
  sm: `calc(${theme.spacing(1)} * 10)`,
  md: `calc(${theme.spacing(2)} * 10)`,
}),

If a lot of your properties need to use the callback:

sx={{
  paddingRight: (theme) => theme.spacing(2),
  margin: (theme) => ({
    xs: theme.spacing(0),
    sm: theme.spacing(2),
  }),
  '& .child': {
    color: (theme) => theme.palette.primary.contrastText,
    bgcolor: (theme) => theme.palette.primary.main,
  },
}}

You can use this trick to simplify them:

sx={{
  '&': (theme) => ({
    paddingRight: theme.spacing(2),
    margin: {
      xs: theme.spacing(0),
      sm: theme.spacing(2),
    },
    '& .child': {
      color: theme.palette.primary.contrastText,
      bgcolor: theme.palette.primary.main,
    },
  }),
}}

Remember when I said something about the properties being theme aware? The code above can be simplified thanks to the tight integration with MUI theme:

sx={{
  pr: 2,
  m: {
    xs: 0,
    sm: 2,
  },
  '& .child': {
    color: 'primary.contrastText',
    bgcolor: 'primary.main',
  },
}}

Codesandbox Demo

like image 195
NearHuscarl Avatar answered Sep 17 '25 02:09

NearHuscarl