Search code examples
cssreactjsresponsive-designcss-gridstyled-components

Responsive css grid with fixed rows and maximum columns but can show more items


I'm trying to create a grid component where the layout is 2 rows and x columns. Columns can be max 6 and the grid items are react children of unknown amount, hence the x columns.

I got a grid down but I'm not sure how to handle the last item since that needs to be a button which displays more grid items once clicked.

This is what I have for the grid right now:

const gridOverflowStyles = css`
  overflow-y: hidden;
  grid-auto-rows: 0;
  grid-template-rows: repeat(2, 1fr);
  justify-content: space-between;
`;

type GridProps = {
    gridItemArr: gridItem[];
}

const Grid = styled.div<GridProps>`
  display: grid;
  gap: var(--spacing-xs) var(--spacing-2xs);
  grid-template-columns: repeat(auto-fit, 170px);

  /* a media query function */
  ${MQ("desktop")} {
    grid-template-columns: repeat(auto-fit, 200px);
  }

  ${({ gridItemArr }) =>
    gridItemArr.length > 11 && gridOverflowStyles}
`;

And the React component looks something like this:

const arr = Array.from(
  { length: 12 },
  () => gridItemsArr
);

<Grid>
  {arr.map((item, index) => (
    <GridItem
      key={index}
    />
  ))}
</Grid>

On arr.lenght of 12 the grid component shows 2x6 items on full screen width but goes down to 2x5 to 2x4 and 2x3 on smaller screens because the GridItems have a fixed max-width, and on all those different viewports the last item in the grid needs to be a button which expands the grid to show all 12 GridItems.

I'm using Emotion styled component, React and TypeScript.

I have tried looking up different ways of using grid and targeting grid items but I can't find a solution that works for my specific problem. Most likley because I'm a junior Frontend dev.


Solution

  • SOLVED! By adding grid-area styling to the button

    const ShowAllButton = styled(Button.SquareButton)`
      grid-area: 2 / -2 / 2 / -1;
    `;