Search code examples
reactjsmaterial-uiscrollbarhorizontal-scrolling

How to implement horizontal scrolling of tiles in MUI GridList?


This is my JS page where I need to implement the GridList component to show multiple tiles and is scrollable horizontally after list size crosses screen limits.

import React,{ useState} from "react";
import Header from "../../common/header/Header";
import "./Home.css";
import { GridList, GridListTile, GridListTileBar} from "@material-ui/core";

const images = [
    { thumbnail: { uri: 'https://lorempixel.com/200/200/animals',name:'animals'}},
    { thumbnail: { uri: 'https://lorempixel.com/200/200/city'  ,name:'city'}},
    { thumbnail: { uri: 'https://lorempixel.com/200/200/city'  ,name:'city'}},
    { thumbnail: { uri: 'https://lorempixel.com/200/200/city'  ,name:'city'}},
    { thumbnail: { uri: 'https://lorempixel.com/200/200/nature'  ,name:'nature'} },
    { thumbnail: { uri: 'https://lorempixel.com/200/200/cats'  ,name:'cats'} },
    { thumbnail: { uri: 'https://lorempixel.com/200/200/cats'  ,name:'cats'} },
    { thumbnail: { uri: 'https://lorempixel.com/200/200/cats'  ,name:'cats'} },
  ];

export default function Home() {
  return (
    <>
      <Header></Header>
      <header className="head">Upcoming Movies</header>
        <GridList cellHeight={180} cols={6}>
            {images.map((image) => (
            <GridListTile>
                <img src={image.thumbnail.uri} />
                <GridListTileBar
                    title={ image.thumbnail.name}
                />
            </GridListTile>
            ))}
        </GridList>
    </>
  );
}

Solution

  • Note: In the newer versions of MUI, GridList's been changed to ImageList, the code below uses the latest API.

    You can fill the column instead of row by using the code below:

    <ImageList
      sx={{
        gridAutoFlow: "column",
        gridTemplateColumns: "repeat(auto-fill,minmax(160px,1fr)) !important",
        gridAutoColumns: "minmax(160px, 1fr)"
      }}
    >
      {images.map((image) => (
        <ImageListItem>
          <img src={image.thumbnail.uri} />
          <ImageListItemBar title={image.thumbnail.name} />
        </ImageListItem>
      ))}
    </ImageList>
    
    • gridAutoFlow: 'column': Tell the grid to create another column if there is no space left instead of going to the next row.
    • gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))': Set the column min and max width, min is 160px, if there is more than enough space (no need for horizontal scrollbar), set each column width equally.
    • gridAutoColumns: 'minmax(160px, 1fr)': Same as above but for the columns outside of the viewport.

    Live Demo

    V5

    Codesandbox Demo

    V4

    Codesandbox Demo

    References