Ankit Jaishwal
Ankit Jaishwal

Reputation: 526

MUI: How to prevent Grid items from going on next row?

I am using MUI Grid structure in ReactJs to display 5 columns like this:

enter image description here

In smaller screens the columns are moving in the next row. But In smaller screens I also want all the columns to show in one row only and I can access other columns by scrolling horizontally.

<Grid
  container
  spacing={2}
  style={{
    maxHeight: "100vh",
    overflowY: "auto",
    overflowX: "hidden",
    height: "440px",
    overflow: "auto",
  }}
>
  <Grid item xs={2.1}>
    {cards.map((card) => <Card props={card} /> )}
  </Grid>
</Grid>

Upvotes: 15

Views: 21954

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81803

Because Grid uses flexbox under the hood. You can simply set the wrap value to nowrap in your Grid container, you can see the full API of Grid component here.

<Grid
  container
  wrap="nowrap" // --> add this line to disable wrap
  sx={{ overflow: "auto" }} // --> add scrollbar when the content inside is overflowed
  spacing={8}
>
  {...}
</Grid>

Live Demo

Edit 66944361/how-to-prevent-columns-to-go-on-next-row-in-material-ui-grid-structure

Upvotes: 31

yun_jay
yun_jay

Reputation: 1180

The Grid is based on a 12-column grid layout. Therefore xs accepts only the following values:

'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12.

I would recommend you to place an empty grid with an xs size equal to 1 at the beginning and end. That brings you to a total size of xs equal to 12.

          <Grid
            container
            spacing={2}
            style={{
              maxHeight: "100vh",
              overflowY: "auto",
              overflowX: "hidden",
              height: "440px",
              overflow: "auto",
            }}
          >
               <Grid item xs={1}/>
                 {cards.map((card) => (
                   <Grid item xs={2}>
                     <Card props={card} />
                   </Grid>
                  ))}
               <Grid item xs={1}/>
          </Grid>

Upvotes: 1

Related Questions