Render grid items in one row - ReactJS and Material-UI

8.2k views Asked by At

I want to create a material ui carousel that has 3 items visible in the same row. When shrinking the browser's width I want the items to be still in one row and just hide the ones who don't fit.

This is when full screen:

enter image description here

This is what i want to have:

enter image description here

But this is what i get instead:

enter image description here

Do you have any ideas about what am I doing wrong? Here is my code:

  <Paper variant="outlined" className={classes.paper}>
    <Grid
      container
      spacing={2}
      className={classes.grid}
      alignItems="center"
      justify="center"
    >
      ...
      <Box display="flex" alignItems="center" className={classes.box}>
        <Grid item xs="auto" className={classes.arrow}>
          ...Left Arrow...
        </Grid>
        <Grid item>
          <Grid
            container
            spacing={2}
            className={classes.grid}
            alignItems="center"
            justify="center"
          >
            <Grid item xs="auto">
              <UserCard content={users[index]} />
            </Grid>
            <Hidden xsDown>
              <Grid item xs="auto">
                <UserCard content={users[index + 1]} />
              </Grid>
            </Hidden>
            <Hidden smDown>
              <Grid item xs="auto">
                <UserCard content={users[index + 2]} />
              </Grid>
            </Hidden>
          </Grid>
        </Grid>
        <Grid item xs="auto" className={classes.arrow}>
          ...Right Arrow...
        </Grid>
      </Box>
    </Grid>
  </Paper>

Styles

const useStyles = makeStyles((theme) => ({
  paper: {
    display: "flex",
    width: "auto",
  },
  grid: {
    width: "auto",
  },
  arrow: {
    padding: theme.spacing(3),
  },
  box: {
    padding: theme.spacing(3),
  },
}));
2

There are 2 answers

0
MrJadeja On BEST ANSWER

On your Grid container add wrap='nowrap' prop. Which overwrite the default wrap='wrap'.

<Grid
    container
    wrap='nowrap'
    // Your other props
>

Explanation
By default, if items doesn't fit in the container, they simply wrap and move to the next row.

With wrap='nowrap' prop, Grid items stay on the same row.

0
Mikhail Grechka On

You can use useMediaQuery provided by Material UI to check if you need to render the last component

https://material-ui.com/components/use-media-query/