How to dynamically increase or decrease MUI Grid column size?

Viewed 56

Wanted to widen Part 2 dynamically so xs or part 1 becomes 3 and part 2 becomes 9:

<Grid container>
  <Grid item xs={6}>Part 1</Grid>
  <Grid item xs={6}>Part 2</Grid>
</Grid>

I tried to use state to keep the value but got error as

<Grid item xs={{sizeOfPanel}}>

Please help

1 Answers
xs={{sizeOfPanel}}

The code above means passing an object with the property sizeOfPanel to the xs prop, but because xs is a boolean or a GridSize (not an object), I assume this is what you mean:

xs={sizeOfPanel}

EDIT: For typescript users, since xs from Grid accepts a GridSize (1 -> 12 constants), not just any number, so to fix the type error, you have to assert the type for dynamic values:

import Grid, { GridSize } from "@mui/material/Grid";
xs={sizeOfPanel as GridSize}

Here is a full example for you to reference:

const [xs, setXs] = React.useState(6);

return (
  <Box sx={{ flexGrow: 1 }}>
    <Button
      variant="contained"
      onClick={() => setXs((xs) => (xs === 12 ? 0 : ++xs))}
    >
      update
    </Button>
    <Grid container spacing={2}>
      <Grid
        item
        xs={xs as GridSize}
        sx={
          xs === 0 && {
            display: "none"
          }
        }
      >
        <Item>xs={xs}</Item>
      </Grid>
      <Grid
        item
        xs={(12 - xs) as GridSize}
        sx={
          xs === 12 && {
            display: "none"
          }
        }
      >
        <Item>xs={12 - xs}</Item>
      </Grid>
    </Grid>
  </Box>
);

Live Demo

Codesandbox Demo

Related