# Virtual Card Grid

> Thousands of cards in a scrolling grid that draws only the ones in view, with as many columns as fit.

Page: https://uicontext.com/docs/components/virtual-card-grid

Group: Records.

## When to use

Thousands of cards in a scrolling grid that draws only the ones in view, with as many columns as fit. Use [Gallery](https://uicontext.com/docs/components/gallery.md) instead when there are at most a few hundred cards.

## Usage

```ts
import { VirtualCardGrid } from "./ui/uicontext/components/VirtualCardGrid.ts"

const Message = UiSchema.TaggedEnum({ Resized: { width: Schema.Number } })

export const Products = (h: Html.H<typeof Message.Type>, width: number, names: ReadonlyArray<string>) =>
	VirtualCardGrid(h, { label: "Products", count: names.length, width, onResize: (w) => Message.Resized({ width: w }), item: (i) => h.div.children(names[i] ?? "") })
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### A photo library

The example the page opens with: Virtual Card Grid in “A photo library”.

```ts title="src/demo.ts" source="www/src/examples/virtual-card-grid/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"
import { VirtualCardGrid } from "./ui/uicontext/components/VirtualCardGrid.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.sm, inlineSize: "100%" },
	bar: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: space.md, fontSize: font.sm, color: color.muted, fontVariantNumeric: "tabular-nums" },
	jump: { display: "flex", gap: space.xs },
	card: {
		display: "grid",
		gridTemplateRows: "minmax(0, 1fr) auto",
		margin: 0,
		blockSize: "100%",
		overflow: "hidden",
		borderWidth: stroke.hairline,
		borderStyle: "solid",
		borderColor: color.line,
		borderRadius: corner.card,
		backgroundColor: color.panel,
	},
	image: { minBlockSize: 0, backgroundImage: "linear-gradient(160deg, color-mix(in srgb, var(--tone) 35%, white), var(--tone))" },
	meta: { display: "grid", gap: 2, paddingBlock: space.sm, paddingInline: space.md },
	name: { fontSize: font.sm, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
	detail: { fontSize: font.xs, color: color.muted, fontVariantNumeric: "tabular-nums" },
	button: {
		paddingBlock: space.xs,
		minBlockSize: { default: 0, "@media (pointer: coarse)": 44 },
		minInlineSize: { default: 0, "@media (pointer: coarse)": 44 },
		paddingInline: space.sm,
		borderWidth: stroke.control,
		borderStyle: "solid",
		borderColor: color.line,
		borderRadius: corner.control,
		backgroundColor: color.panel,
		color: color.fg,
		fontFamily: "inherit",
		fontSize: font.xs,
		cursor: "pointer",
	},
})

const count = 4_800
const tones = ["#f97316", "#38bdf8", "#a855f7", "#fb7185", "#84cc16", "#94a3b8"]
const places = ["Lisbon", "Kyoto", "Oaxaca", "Tromsø", "Cape Town", "Hobart", "Reykjavík", "Valparaíso"]
// a photo's details from its number, so 4,800 cards need no data up front
const photo = (i: number) => ({
	name: `IMG_${String(2041 + i).padStart(5, "0")}.heic`,
	place: places[i % places.length] ?? "",
	date: `${(i % 28) + 1} ${["Jan", "Feb", "Mar", "Apr", "May", "Jun"][Math.floor(i / 28) % 6]} 2026`,
	tone: tones[i % tones.length] ?? "",
})

const Message = UiSchema.TaggedEnum({ Resized: { width: Schema.Number }, Jumped: { index: Schema.Number } })

// a photo library of 4,800 pictures: only the cards near the view are drawn
export const PhotoLibrary = Html.component({
	name: "PhotoLibrary",
	model: Schema.Struct({ width: Schema.Number, jump: Schema.optional(Schema.Number) }),
	message: Message,
}).make({
	init: () => ({ width: 0 }),
	update: {
		Resized: ($, { width }) => $.evolve({ width }),
		Jumped: ($, { index }) => $.evolve({ jump: index }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			h.div.attrs(sx(styles.bar)).children(
				h.span.attrs({ dir: "auto" }).children(`${count.toLocaleString("en-US")} photos`),
				h.div.attrs(sx(styles.jump)).children(
					h.button.attrs({ type: "button", ...sx(styles.button) }).on("click", Message.Jumped({ index: 0 })).children("First"),
					h.button.attrs({ type: "button", ...sx(styles.button) }).on("click", Message.Jumped({ index: 2_400 })).children("Middle"),
					h.button.attrs({ type: "button", ...sx(styles.button) }).on("click", Message.Jumped({ index: count - 1 })).children("Last"),
				),
			),
			VirtualCardGrid(h, {
				key: "photos",
				label: "Photos",
				count,
				width: model.width,
				onResize: (width) => Message.Resized({ width }),
				minWidth: 180,
				rowHeight: 200,
				height: "440px",
				...(model.jump === undefined ? {} : { scrollToIndex: model.jump }),
				item: (i) => {
					const p = photo(i)
					return h.figure.attrs(sx(styles.card)).children(
						h.div.attrs({ role: "img", "aria-label": `${p.place}, ${p.date}`, ...sx(styles.image) }).style({ "--tone": p.tone }),
						h.figcaption.attrs(sx(styles.meta)).children(h.span.attrs(sx(styles.name)).children(p.name), h.span.attrs(sx(styles.detail)).children(`${p.place} · ${p.date}`)),
					)
				},
			}),
		),
})
```

### A company directory

Short rows with `rowHeight: 76`; columns at least `minWidth` wide fill the space.

This example also uses Avatar. Install it too:

```sh
npx shadcn@latest add checkfu/uicontext/avatar
```

```ts title="src/people.ts" source="www/src/examples/virtual-card-grid/people.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Avatar } from "./ui/uicontext/components/Avatar.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"
import { VirtualCardGrid } from "./ui/uicontext/components/VirtualCardGrid.ts"

const styles = stylex.create({
	wrap: { inlineSize: "100%" },
	card: {
		display: "grid",
		gridTemplateColumns: "auto minmax(0, 1fr)",
		alignItems: "center",
		gap: space.md,
		blockSize: "100%",
		boxSizing: "border-box",
		paddingInline: space.md,
		borderWidth: stroke.hairline,
		borderStyle: "solid",
		borderColor: color.line,
		borderRadius: corner.card,
		backgroundColor: color.panel,
	},
	text: { display: "grid", gap: 2, minInlineSize: 0 },
	name: { fontSize: font.sm, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
	role: { fontSize: font.xs, color: color.muted, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
})

const first = ["Ada", "Priya", "Kenji", "Tomás", "Amara", "Lena", "Omar", "Sofia", "Wei", "Noah", "Ines", "Ravi"]
const last = ["Okafor", "Raman", "Watanabe", "García", "Nwosu", "Fischer", "Haddad", "Rossi", "Chen", "Kim", "Silva", "Patel"]
const roles = ["Engineering", "Design", "Sales", "Support", "Finance", "Marketing", "Data", "Legal"]
const person = (i: number) => ({
	name: `${first[i % first.length]} ${last[Math.floor(i / first.length) % last.length]}`,
	role: `${roles[i % roles.length]} · ${["Lisbon", "Berlin", "Toronto", "Singapore"][i % 4]}`,
})

const Message = UiSchema.TaggedEnum({ Resized: { width: Schema.Number } })

// a company directory of 1,200 people, in short cards
export const Directory = Html.component({
	name: "Directory",
	model: Schema.Struct({ width: Schema.Number }),
	message: Message,
}).make({
	init: () => ({ width: 0 }),
	update: { Resized: ($, { width }) => $.evolve({ width }) },
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			VirtualCardGrid(h, {
				key: "people",
				label: "People",
				count: 1_200,
				width: model.width,
				onResize: (width) => Message.Resized({ width }),
				minWidth: 220,
				rowHeight: 76,
				height: "360px",
				item: (i) => {
					const p = person(i)
					return h.div.attrs(sx(styles.card)).children(
						Avatar(h, { id: String(i), name: p.name, size: "md", decorative: true }),
						h.div.attrs(sx(styles.text)).children(h.span.attrs(sx(styles.name)).children(p.name), h.span.attrs(sx(styles.role)).children(p.role)),
					)
				},
			}),
		),
})
```

## API reference

**Options**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `key` | `string` | — | Names the instance among others in the same view; needed for more than one. |
| `label` (required) | `string` | — | What the cards are: "Photos". |
| `count` (required) | `number` | — | — |
| `width` (required) | `number` | — | The grid's measured width; 0 before it's measured, which draws for `fallbackWidth`. |
| `onResize` (required) | `(width: number) => Message` | — | — |
| `item` (required) | `(index: number) => View.Content` | — | Draws the card at an index. |
| `minWidth` | `number` | `200` | The narrowest a column gets, in pixels; 200 by default. |
| `rowHeight` | `number` | `240` | A row's height, card and gap together, in pixels; 240 by default. |
| `height` | `string` | `"480px"` | The scrolling box's height; "480px" by default. |
| `fallbackWidth` | `number` | `960` | The width to lay out for before the first measure; 960 by default. |
| `scrollToIndex` | `number` | — | Scrolls to the row holding this card. |
| `style` | `Style` | — | — |

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/virtual-card-grid
```

With npm: `npx shadcn@latest add checkfu/uicontext/virtual-card-grid`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/virtual-card-grid`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/virtual-card-grid`.

It writes these files:

- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/VirtualCardGrid.ts`
- `src/ui/uicontext/components/charts/Data.ts`
- `src/ui/uicontext/components/charts/Format.ts`
- `src/ui/uicontext/components/charts/Frame.ts`
- `src/ui/uicontext/components/charts/Scale.ts`
- `src/ui/uicontext/components/charts/chart.stylex.ts`
- `src/ui/uicontext/components/charts/slots.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/VirtualCardGrid.ts](https://github.com/checkfu/uicontext/blob/main/src/VirtualCardGrid.ts)

## Related

- [Data Grid](https://uicontext.com/docs/components/data-grid.md) (`data-grid`): A spreadsheet-like grid for editing records, with typed columns, sorting and grouping.
- [Pivot Table](https://uicontext.com/docs/components/pivot-table.md) (`pivot-table`): Records summed two ways, such as revenue by region and quarter, with totals on both edges and cells tinted by size.
- [Table](https://uicontext.com/docs/components/table.md) (`table`): A simple read-only table with a caption, row headers and an empty state.
- [Group Header](https://uicontext.com/docs/components/group-header.md) (`group-header`): The line over a group of rows with its count, sticky while they scroll, folding the group.
- [Description List](https://uicontext.com/docs/components/description-list.md) (`description-list`): A record's facts as label and value pairs, in rows or columns, with Copy for ids.
- [Fact Grid](https://uicontext.com/docs/components/fact-grid.md) (`fact-grid`): A few numbers about one thing, such as a customer's plan and seats, as small tiles.
