# Infinite Scroll

> Load the next page when a sentinel scrolls into view, with a loading row, an end of list message and a Load more button as the accessible fallback.

- Kind: Component (Tables)
- Docs: https://ui.minidev.pro/docs/infinite-scroll
- Source (registry JSON with the full file): https://ui.minidev.pro/r/infinite-scroll.json
- License: MIT. One file, yours to edit after install.

## When to use

It uses IntersectionObserver, never fires twice for the same page, shows a loading row and an end-of-list message, keeps a real "Load more" button as the accessible fallback, and offers Retry when a page fails. Use it for feeds of unknown length. For thousands of rows already in memory use VirtualList, and for numbered pages use Pagination.

## Installation

### shadcn CLI (copies the source into your project)

```bash
npx shadcn@latest add @minidev/infinite-scroll
```

Writes `components/ui/infinite-scroll.tsx` plus the MiniDev files it is built from (button, spinner) and installs its npm dependencies. Older CLI versions: `npx shadcn@latest add https://ui.minidev.pro/r/infinite-scroll.json`.

### npm package

```bash
npm i minidev-ui-kit
```

Add the tokens to your global stylesheet once:

```css
@import "tailwindcss";
@import "minidev-ui-kit/styles.css";
@source "../node_modules/minidev-ui-kit";
```

Next.js also needs `transpilePackages: ["minidev-ui-kit"]` in next.config.

## Import

After the shadcn install:

```tsx
import { InfiniteScroll } from "@/components/ui/infinite-scroll"
```

From the npm package:

```tsx
import { InfiniteScroll } from "minidev-ui-kit/ui/infinite-scroll"
```

## Usage

```tsx
import { InfiniteScroll } from "@/components/ui/infinite-scroll"

export function Example() {
  return (
    <InfiniteScroll />
  )
}
```

## Props

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `loadMore` | `(page: number) => Promise<{ items: T[]; hasMore: boolean }>` | - | no | Fetch a page (0-based); return its items and whether more remain. Throw to show Retry. |
| `renderItem` | `(item: T, index: number) => React.ReactNode` | - | no | Renders one item. Each is wrapped in an li. |
| `rootMargin` | `string` | `"240px"` | no | How far before the end to start loading, as a CSS margin. |
| `label` | `string` | `"Results"` | no | Accessible name for the focusable scroll box and the list inside it. |
| `className` | `string` | - | no |  |

## Examples

### Custom loader and rows

loadMore receives the page index and returns the items plus whether more exist; renderItem draws each row.

```tsx
type Customer = { id: string; name: string; email: string }

const NAMES = ["Maya Chen", "Theo Okafor", "Priya Raman", "Sam Lowe", "Noor Haddad", "Elena Petrova", "Jonas Weber", "Aisha Bello"]

const loadCustomers = (page: number) =>
  new Promise<{ items: Customer[]; hasMore: boolean }>((resolve) =>
    setTimeout(() => {
      const items = NAMES.map((name, i) => ({
        id: "cus_" + (page * 8 + i + 1),
        name,
        email: name.toLowerCase().replace(" ", ".") + "@northwind.example",
      }))
      resolve({ items, hasMore: page < 2 })
    }, 600),
  )

<InfiniteScroll
  loadMore={loadCustomers}
  renderItem={(c) => (
    <div className="flex items-center gap-3 rounded-lg border border-border bg-surface px-3 py-2 shadow-xs">
      <Avatar size="sm"><AvatarFallback>{c.name.split(" ").map((p) => p[0]).join("")}</AvatarFallback></Avatar>
      <div className="min-w-0">
        <p className="truncate text-sm text-fg">{c.name}</p>
        <p className="truncate text-xs text-fg-muted">{c.email}</p>
      </div>
    </div>
  )}
/>
```

### Short list that ends

Return hasMore false from the last page and the end of list message replaces the loader; rootMargin starts fetching earlier.

```tsx
type Payment = { id: string; invoice: string; amount: string; status: "paid" | "failed" }

const loadPayments = (page: number) =>
  new Promise<{ items: Payment[]; hasMore: boolean }>((resolve) =>
    setTimeout(() => {
      const items = Array.from({ length: 6 }, (_, i): Payment => {
        const n = page * 6 + i
        return { id: "pay_" + n, invoice: "INV-" + (2041 - n), amount: "$" + (1200 + n * 85).toLocaleString() + ".00", status: n % 5 === 3 ? "failed" : "paid" }
      })
      resolve({ items, hasMore: page < 1 })
    }, 500),
  )

<InfiniteScroll
  loadMore={loadPayments}
  rootMargin="80px"
  className="h-64"
  renderItem={(p) => (
    <div className="flex items-center justify-between rounded-lg border border-border bg-surface px-3 py-2 text-sm shadow-xs">
      <span className="font-mono text-xs text-fg">{p.invoice}</span>
      <span className="tabular-nums text-fg-muted">{p.amount}</span>
      <Badge variant={p.status === "failed" ? "destructive" : "secondary"}>{p.status}</Badge>
    </div>
  )}
/>
```

## Keyboard interactions

| Key | Action |
| --- | --- |
| `Tab` | Focuses the scroll box, then moves through focusable content in the items and on to the Load more or Retry button. |
| `ArrowUp` or `ArrowDown` | With the scroll box focused, scrolls the list. |
| `Enter` or `Space` | On Load more, fetches the next page. On Retry, repeats the failed request. |

## Accessibility

- The scroll box is a focusable `role="region"` with a focus ring, so it can be scrolled from the keyboard even when the items hold nothing focusable.
- The region and the `ul` inside it are both named by `label` ("Results" by default). The `ul` has `aria-busy` while a page loads.
- The status line is `aria-live="polite"`, so "Loading more", "Could not load more." and "You have reached the end" are announced.
- The scroll sentinel is `aria-hidden`; keyboard and screen reader users load pages with the real Load more button instead.

## FAQ

### How do I use InfiniteScroll with a cursor-based API?

`loadMore(page)` receives a 0-based page number and must resolve `{ items, hasMore }`. For cursors, keep the last cursor in a ref inside your loader and return `hasMore: Boolean(res.nextCursor)`. The latest `loadMore` is read from a ref, so an inline function does not reset anything.

### What happens when a page fails to load?

Throw or reject in `loadMore`. The list shows "Could not load more." with a Retry button, and stops watching the scroll until Retry is pressed, so a failing API is not called on every scroll.

### How do I start over when the search or filters change?

There is no reset prop; the items and page number are internal state. Remount it with a key: `<InfiniteScroll key={query} loadMore={...} />` loads from page 0 again.

### Why does it scroll inside a box instead of the page?

The component is its own scroll container (`h-80 overflow-y-auto`), and the IntersectionObserver uses that box as its root. Change the height with `className`, such as `className="h-[600px]"`. Scrolling the window instead means changing the observer's `root` in your copy.

## Rules for generating code

- Use semantic tokens only (bg, surface, sunken, border, fg, fg-muted, fg-subtle, ink, accent, success, warning, danger). Never raw hex or palette steps like blue-500.
- Shadows only from the set: shadow-xs, shadow-sm, shadow-raised, shadow-md, shadow-lg, shadow-overlay.
- Numbers use tabular-nums. Dark mode is the `dark` class on <html>; components never branch on theme.

## Dependencies

- Built from: [button](https://ui.minidev.pro/docs/button/md), [spinner](https://ui.minidev.pro/docs/spinner/md)

## Related

- [Virtual List](https://ui.minidev.pro/docs/virtual-list/md): React virtual list that renders only rows in view, with fixed or measured row heights, overscan, arrow key and Page Up/Down navigation and scrollToIndex.
- [Pagination](https://ui.minidev.pro/docs/pagination/md): A pagination nav with Prev and Next buttons that disable at the edges and numbered page buttons that mark the current page with aria-current. Built in React.
- [Virtualized List](https://ui.minidev.pro/docs/virtualized-list/md): Virtualized list that renders only the visible rows plus a small buffer, using a fixed item height and absolute positioning. Keeps thousands of React rows fast.
- [Audit Filter Bar](https://ui.minidev.pro/docs/audit-filter-bar/md): Filter toolbar for audit logs combining a search field, actor filter chips for all, admins or system, and a date range picker in one wrapping row.
- [Audit Log Entry](https://ui.minidev.pro/docs/audit-log-entry/md): Single audit log line: actor avatar, actor name, muted action text and the affected target, with a relative timestamp underneath. Stacks into a trail.
- [Audit Trail](https://ui.minidev.pro/docs/audit-trail/md): Bordered audit trail in React that renders a list of actor, action, target and time records as stacked log entries. Useful for security and admin history pages.

---

All 557 components: https://ui.minidev.pro/llms.txt (full text: https://ui.minidev.pro/llms-full.txt).
