Search code examples
reactjsgrid

react-packed-grid: null child is inserting a grid item


I have a problem that my data is returning an empty div even if it shouldn't display anything, which causes my design to be broken.

      const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    
      const itemsToDisplay = data.slice(0, 5);
      const remainingItemsCount = data.length - itemsToDisplay.length;

      <PackedGrid boxAspectRatio={aspectRatio} className="fullscreen">
        {itemsToDisplay.map((i) => (
          <GridItemPlaceholder>{i}</GridItemPlaceholder>
        ))}
        {remainingItemsCount > 20 ? (
          <GridItemPlaceholder>+{remainingItemsCount}</GridItemPlaceholder>
        ) : null}
      </PackedGrid>`

The case above should return item 5 in the middle of the grid, but instead it's on left side and that's because remainingItemsCount is still returning an empty div on the right side of it. You can inspect the HTML to see it.

I wrote a condition that should stay null, but it does not work. I believe the issue is in the package I am using, but I figure there has to be some solution.

Here is my code example: https://codesandbox.io/s/grid-16-9-ratio-forked-5qt1rx?file=/src/App.js


Solution

  • This does the trick for you

    
      const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    
      const itemsToDisplay = data.slice(0, 5);
      const remainingItemsCount = data.length - itemsToDisplay.length;
      if (remainingItemsCount > 20) {
        itemsToDisplay.push(`+${remainingItemsCount}`)
      }
      return (
        <>
          <PackedGrid boxAspectRatio={aspectRatio} className="fullscreen">
            {itemsToDisplay.map((i) => (
              <GridItemPlaceholder>{i}</GridItemPlaceholder>
            ))}
          </PackedGrid>
        </>
      );