How I add custom breakpoint to sx prop in material ui v5

Viewed 10

We have react app using material ui v4. Now we are trying to upgrade to v5. I had following custom style defined in v4:

const useStyles = makeStyles((theme: Theme) => ({
  container: {
    overflowY: "scroll",
    boxSizing: "border-box",
    [theme.breakpoints.up("sm")]: {
      padding: theme.spacing(2),
    },
    backgroundColor: "white",
  },
  grid: {
    [theme.breakpoints.down("sm")]: {
      width: "100%",
      margin: "auto",
    },
  },
}))

with v5, I changed it to:

const theme = useTheme()
...
<Box
        sx={{
          overflowY: "scroll",
          boxSizing: "border-box",
          [theme.breakpoints.up("sm")]: {
            padding: theme.spacing(2),
          },
          backgroundColor: "white",
        }}
      >
...
 <Grid
          sx={{
            [theme.breakpoints.down("sm")]: {
              width: "100%",
              margin: "auto",
            },
          }}
          container
          spacing={2}
        >

I am not sure if I could directly use theme like above, or I should use callback like:

<Box
        sx={(theme) => ({
          overflowY: "scroll",
          boxSizing: "border-box",
          [theme.breakpoints.up("sm")]: {
            padding: theme.spacing(2),
          },
          backgroundColor: "white",
        })}
      >

As you can see, not all properties depend on theme.

1 Answers

You could just pass value as callback function with theme as the first param

      <Box
        sx={{
          overflowY: "scroll",
          boxSizing: "border-box",
          [theme.breakpoints.up("sm")]: {
            padding: theme => theme.spacing(2),
            //       ^^^^^
          },
          backgroundColor: "white",
        }}
      >
Related