Reactjs – How to make the GridList component in React Material-UI responsive

material-uireactjsresponsive

I'm using the Material-UI version 1 to make the grid UI in my React application. I want to make the grid responsive. The GridList component API has cols props, which by default is 2.

For example, it could looks like this below.

<GridList cols={1} spacing={32} className="list"></GridList>

Can I dynamically change the props? Or are there any other ways to make it responsive?

Best Answer

U can use the layout breakpoints provide by MUI to toggle GridList or GridListTile cols property. The code will look like this:

...
import withWidth, { isWidthUp } from '@material-ui/core/withWidth';
...

const MyComponent = props => {
  const getGridListCols = () => {
    if (isWidthUp('xl', props.width)) {
      return 4;
    }

    if (isWidthUp('lg', props.width)) {
      return 3;
    }

    if (isWidthUp('md', props.width)) {
      return 2;
    }

    return 1;
  }

  return(
    ...
    <GridList spacing={15} cellHeight={400} cols={getGridListCols()}>
      {
        myItemsArray.map(item => (
          <GridListTile key={item} cols={1}>
            <FooBar />
          </GridListTile>
        ))
      }
    </GridList>
    ...
  );
};

...

export default withWidth()(MyComponent);