Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adjust ImageList columns based on screen size?

I've tried using ImageList component instead of Grid as I just need a grid of photos with titles and it seems to be the whole point of ImageList. My issue is that unlike with Grid I cannot pass breakpoint props for different screen sizes (which I find weird as this would seem logical) so that I can get different count of columns on different screens. What would be the best approach to adjust number of columns based on screen size?

like image 547
Stormwaker Avatar asked Feb 03 '26 05:02

Stormwaker


2 Answers

ImageList uses CSS grid and needs the col prop to set the grid-template-columns but without any responsive API baked in. You can swap the ImageList with a Box component with the display set to grid, and uses the sx prop to declare the column template value depend on the screen size, but first let define some breakpoints:

const theme = createTheme({
  breakpoints: {
    values: {
      mobile: 0,
      bigMobile: 350,
      tablet: 650,
      desktop: 900
    }
  }
});

Then in the component, you can start using it like this:

import ImageListItem, { imageListItemClasses } from "@mui/material/ImageListItem";
<ThemeProvider theme={theme}>
  <Box
    sx={{
      display: "grid",
      gridTemplateColumns: {
        mobile: "repeat(1, 1fr)",
        bigMobile: "repeat(2, 1fr)",
        tablet: "repeat(3, 1fr)",
        desktop: "repeat(4, 1fr)"
      }
      // standard variant from here:
      // https://github.com/mui-org/material-ui/blob/3e679ac9e368aeb170d564d206d59913ceca7062/packages/mui-material/src/ImageListItem/ImageListItem.js#L42-L43
      [`& .${imageListItemClasses.root}`]: {
        display: "flex",
        flexDirection: "column"
      }
    }}
  >
    {itemData.map((item) => <ImageListItem {...}/>)}
  </Box>
</ThemeProvider>

Live Demo

Codesandbox Demo

References

  • Media queries in MUI components
  • https://mui.com/customization/breakpoints/#main-content
like image 176
NearHuscarl Avatar answered Feb 04 '26 22:02

NearHuscarl


I used the useMediaQuery hook to get the cols props for the ImageList component.

import { ImageList, ImageListItem, useMediaQuery } from '@mui/material';

function Gallery() {
const matches = useMediaQuery('(min-width:600px)');
return (
    <ImageList cols={matches ? 3 : 2} variant="masonry">
      <ImageListItem>
       ...
      </ImageListItem>
    </ImageList>
  );
}
like image 44
Alyn Augsornworawat Avatar answered Feb 04 '26 21:02

Alyn Augsornworawat