---
title: "Infinite Masonry"
description: "Responsive virtualized masonry that measures variable-height cards and loads more data as the user nears the end."
category: "Blocks"
publishedAt: "2026-07-15"
updatedAt: "2026-11-10"
documentation: "https://beui.dev/components/blocks/infinite-masonry"
markdown: "https://beui.dev/components/blocks/infinite-masonry.md"
license: "MIT"
---

# Infinite Masonry

> Responsive virtualized masonry that measures variable-height cards and loads more data as the user nears the end.

## Install

```bash
npx shadcn@latest add @beui/infinite-masonry
```

## Dependencies

- `@tanstack/react-virtual`
- `clsx`
- `lucide-react`
- `motion`
- `react`
- `tailwind-merge`

## Usage

```tsx
"use client";

import { useCallback, useState } from "react";
import { InfiniteMasonry } from "@/components/motion/infinite-masonry";

type GalleryItem = {
  id: string;
  title: string;
  category: string;
  image: string;
  imageHeight: number;
};

const PAGE_SIZE = 6;
const MAX_ITEMS = 42;

const gallerySource = [
  {
    title: "Soft geometry",
    category: "Architecture",
    image:
      "https://images.unsplash.com/photo-1511818966892-d7d671e672a2?auto=format&fit=crop&w=720&q=80",
    imageHeight: 260,
  },
  {
    title: "Open horizon",
    category: "Landscape",
    image:
      "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?auto=format&fit=crop&w=720&q=80",
    imageHeight: 190,
  },
  {
    title: "Working rhythm",
    category: "Workspace",
    image:
      "https://images.unsplash.com/photo-1497366754035-f200968a6e72?auto=format&fit=crop&w=720&q=80",
    imageHeight: 230,
  },
  {
    title: "Shared table",
    category: "Studio",
    image:
      "https://images.unsplash.com/photo-1524758631624-e2822e304c36?auto=format&fit=crop&w=720&q=80",
    imageHeight: 300,
  },
  {
    title: "In session",
    category: "People",
    image:
      "https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=720&q=80",
    imageHeight: 210,
  },
  {
    title: "After hours",
    category: "Office",
    image:
      "https://images.unsplash.com/photo-1504384308090-c894fdcc538d?auto=format&fit=crop&w=720&q=80",
    imageHeight: 280,
  },
] as const;

function createItems(start: number, count: number): GalleryItem[] {
  return Array.from({ length: count }, (_, offset) => {
    const index = start + offset;
    const source = gallerySource[index % gallerySource.length];

    return {
      ...source,
      id: `gallery-${index}`,
      title: `${source.title} ${Math.floor(index / gallerySource.length) + 1}`,
    };
  });
}

export function InfiniteMasonryPreview() {
  const [items, setItems] = useState(() => createItems(0, 12));
  const [loading, setLoading] = useState(false);
  const hasMore = items.length < MAX_ITEMS;

  const loadMore = useCallback(async () => {
    if (loading || !hasMore) return;
    setLoading(true);

    await new Promise((resolve) => setTimeout(resolve, 650));
    setItems((current) => {
      const count = Math.min(PAGE_SIZE, MAX_ITEMS - current.length);
      return count > 0
        ? [...current, ...createItems(current.length, count)]
        : current;
    });
    setLoading(false);
  }, [hasMore, loading]);

  return (
    <div className="w-full max-w-5xl">
      <div className="mb-3 flex items-end justify-between gap-4 px-1">
        <div>
          <p className="text-sm font-medium text-foreground">Visual index</p>
          <p className="mt-0.5 text-xs text-muted-foreground">
            Scroll to load the next page
          </p>
        </div>
        <p className="font-mono text-xs tabular-nums text-muted-foreground">
          {items.length} items
        </p>
      </div>

      <InfiniteMasonry
        items={items}
        getItemKey={(item) => item.id}
        renderItem={(item) => (
          <figure className="overflow-hidden rounded-2xl border border-border bg-card">
            <div
              className="relative w-full overflow-hidden"
              style={{ height: item.imageHeight }}
            >
              <img
                src={item.image}
                alt={item.title}
                loading="lazy"
                decoding="async"
                className="absolute inset-0 size-full object-cover"
              />
            </div>
            <figcaption className="flex items-start justify-between gap-3 p-3">
              <p className="text-sm font-medium text-foreground">
                {item.title}
              </p>
              <p className="shrink-0 text-[11px] uppercase tracking-wider text-muted-foreground">
                {item.category}
              </p>
            </figcaption>
          </figure>
        )}
        onLoadMore={loadMore}
        hasMore={hasMore}
        loading={loading}
        estimateSize={(item) => item.imageHeight + 66}
        ariaLabel="Visual inspiration gallery"
        className="h-[34rem]"
      />
    </div>
  );
}
```

## API Reference

### InfiniteMasonry

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `items` | `readonly T[]` |  | Yes | The items loaded so far, in feed order. |
| `getItemKey` | `(item: T, index: number) => InfiniteMasonryKey` |  | Yes | Returns a stable unique key for an item. |
| `renderItem` | `(item: T, index: number) => ReactNode` |  | Yes | Renders one item's card. |
| `onLoadMore` | `() => void \| Promise<void>` |  | Yes | Called when the scroll nears the end and more items should load. |
| `hasMore` | `boolean` |  | Yes | Whether more items can load. False shows `endState` after the last item. |
| `loading` | `boolean` | `false` | No | Shows loading placeholders at the end while more items load. Default: false |
| `error` | `ReactNode` |  | No | Error shown in a card at the end. Pauses loading while set. |
| `onRetry` | `(() => void)` |  | No | Called from the error card's retry button. The button shows only when set. |
| `estimateSize` | `((item: T, index: number) => number)` | `() => 240` | No | Estimated item height in px before it is measured. Default: 240 |
| `renderLoadingItem` | `((index: number) => ReactNode)` | `(index) => <DefaultLoadingItem index={index} />` | No | Renders a loading placeholder card while more items load. |
| `emptyState` | `ReactNode` |  | No | Shown when there are no items and nothing more to load. |
| `endState` | `ReactNode` |  | No | Shown below the last item once `hasMore` is false. |
| `minColumnWidth` | `number` | `208` | No | Smallest column width in px before a column is dropped. Default: 208 |
| `maxColumns` | `number` | `4` | No | Most columns to show. Default: 4 |
| `gap` | `number` | `12` | No | Space between items in px. Default: 12 |
| `overscan` | `number` | `4` | No | Rows to render past the viewport, per column. Default: 4 |
| `prefetch` | `number` | `3` | No | Starts loading when this many items from the end are visible. Default: 3 |
| `animateItems` | `boolean` | `true` | No | Fades and slides in items added after the first render. Default: true |
| `ariaLabel` | `string` |  | No | Accessible name for the feed. Default: "Infinite masonry feed" |
| `className` | `string` |  | No | Classes merged onto the scroll container. |
| `contentClassName` | `string` |  | No | Classes merged onto the inner content element that holds the items. |
| `itemClassName` | `string` |  | No | Classes merged onto each item wrapper, not loading or error cards. |
| `labels` | `Partial<{ label: string; emptyTitle: string; emptyDescription: string; loadError: string; retry: string; loadingMore: string; }>` |  | No | Override any built-in string. |

## About Infinite Masonry

Infinite Masonry is a responsive, virtualized masonry grid for React that measures each card's real height, fits as many lanes as the width allows, and calls onLoadMore as the reader nears the end. Only cards near the viewport are rendered, so long feeds stay fast, and newly loaded cards rise into place with a short staggered spring. It includes loading placeholders, an error card with retry, an empty state and an end state, and is built with Framer Motion and Tailwind CSS.

### When to use it

- An image gallery, moodboard or portfolio shows mixed-height cards in an endless feed.
- A social or inspiration feed loads posts page by page as the user scrolls.
- A search results page lays out cards of different lengths without wasting vertical space.

### Accessibility

The feed is a section with an aria-label ("Infinite masonry feed" by default, set with ariaLabel) that sets aria-busy while loading, and a polite live region announces "Loading more items". Placeholder cards are hidden from assistive technology, and a failed page shows a "Try again" button when you pass onRetry. With reduced motion enabled, new cards appear in place without the rise.

### FAQ

**How do I make an infinite scroll masonry grid in React?**

Pass items, getItemKey, renderItem, onLoadMore and hasMore, and set loading while a page is being fetched. prefetch (3 by default) controls how close to the end the next load starts.

**How do I control the number of columns?**

minColumnWidth (208 by default) and maxColumns (4 by default) decide how many lanes fit, and gap sets the spacing. estimateSize gives a starting height for each card before it is measured.

**Can I turn off the card entrance animation?**

Yes. Set animateItems to false. Cards that are already present when the grid mounts never animate, so only items loaded later rise in.

## Source

- Registry detail: https://beui.dev/r/infinite-masonry
- Raw source: https://beui.dev/r/infinite-masonry/raw
- GitHub: https://github.com/starc007/ui-components
