Shadcn Repeater
A list of repeatable form rows, such as invoice lines, product variants or team invites. Users add, remove and reorder rows with the pointer or the keyboard. The repeater keeps track of row order, enforces min and max, moves focus to the right place after every change and announces it to screen readers. Your own state keeps the row data.
Installation
npx shadcn@latest add @shadcnuikit/repeater1
This adds components/ui/repeater.tsx, the button component it depends on, and a demo file. Set up the registry once as described in Shadcn CLI. Repeater is free and installs without an API key.
Manual installation
Install the dependencies and the button component:
npm install @ui-sdk/core@beta @ui-sdk/react@beta lucide-react
npx shadcn@latest add button
Copy the source into components/ui/repeater.tsx:
"use client";
import * as React from "react";import { announce, createChange, createReorder, definePrimitive, elements, keepFocus, type ChangeDetails, type ReorderDraft, type ReorderReason,} from "@ui-sdk/core";import { createParts } from "@ui-sdk/react/primitive";import { GripVerticalIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";
type RepeaterReason = "add" | "remove" | ReorderReason;
type RepeaterOptions = { value?: string[]; defaultValue?: string[]; onValueChange?: (value: string[], details: ChangeDetails<RepeaterReason>) => void; min?: number; max?: number; disabled?: boolean; itemLabel?: string; createKey?: () => string;};
type RepeaterState = { value: string[]; moving: ReorderDraft | null; min: number; max: number | null; disabled: boolean; itemLabel: string;};
const fieldSelector = "input:not([type=hidden]), textarea, select, [role=combobox], [contenteditable=true]";
function defaultKey() { return globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2);}
// keepFocus only steps in when focus is lost; after an add the Add button keeps it,// so wait for the new row to render and move focus there ourselves.function focusWhenRendered(find: () => HTMLElement | null | undefined, from: Element | null) { let frames = 0; const attempt = () => { if (from && from.ownerDocument.activeElement !== from) return; const el = find(); if (el) { el.focus(); return; } if (frames++ < 10) requestAnimationFrame(attempt); }; requestAnimationFrame(attempt);}
function canAdd(state: RepeaterState) { return !state.disabled && (state.max === null || state.value.length < state.max);}
function canRemove(state: RepeaterState) { return !state.disabled && state.value.length > state.min;}
const repeater = definePrimitive({ name: "repeater", options: { value: "list", defaultValue: "list", onValueChange: "callback", min: "number", max: "number", disabled: "boolean", itemLabel: "string", createKey: "value", }, controlled: ["value"], state: (options: RepeaterOptions): RepeaterState => ({ value: options.value ?? options.defaultValue ?? [], moving: null, min: options.min ?? 0, max: options.max ?? null, disabled: options.disabled ?? false, itemLabel: options.itemLabel ?? "Item", }), sync: (options) => ({ ...(options.value === undefined ? {} : { value: options.value }), min: options.min ?? 0, max: options.max ?? null, disabled: options.disabled ?? false, itemLabel: options.itemLabel ?? "Item", }), api: (context) => { const change = createChange(context); const position = (key: string): number => { const state = context.store.get(); return (state.moving?.order ?? state.value).indexOf(key) + 1; }; const reorder = createReorder(context, { slot: "item", key: "value", draft: "moving", set: (value, details) => change("value", value, details), disabled: () => context.store.get().disabled, label: (key) => `${context.store.get().itemLabel} ${position(key)}`, });
const focusInside = () => { const root = context.element("root"); return !!root && root.contains(root.ownerDocument.activeElement); };
return { reorder, add(event?: Event) { const state = context.store.get(); if (!canAdd(state)) return false; const key = (context.options().createKey ?? defaultKey)(); const added = change("value", [...state.value, key], { reason: "add", event }); if (!added) return false; announce(`${state.itemLabel} ${state.value.length + 1} added`); if (focusInside()) { const root = context.element("root"); focusWhenRendered(() => { const item = context.element("item", key); return item?.querySelector<HTMLElement>(fieldSelector); }, root?.ownerDocument.activeElement ?? null); } return true; }, remove(key: string, event?: Event) { const state = context.store.get(); if (!canRemove(state)) return false; const index = state.value.indexOf(key); if (index === -1) return false; const removed = change( "value", state.value.filter((item) => item !== key), { reason: "remove", event }, ); if (!removed) return false; announce(`${state.itemLabel} ${index + 1} removed`); if (focusInside()) { // The pressed button leaves with its row, so focus the row that takes its place. keepFocus(() => { const buttons = elements(context, "item-remove").filter((part) => part.key !== key); return (buttons[index] ?? buttons.at(-1))?.el ?? context.element("add") ?? undefined; }); } return true; }, }; }, slots: (slot) => ({ root: slot({ role: "group", attrs: (state) => ({ "data-disabled": state.disabled ? "" : undefined, }), }), list: slot<{}, { order: string[] }>({ role: "list", state: (state, part) => ({ order: part.api.reorder.order(state) }), attrs: (state) => ({ "data-empty": state.value.length === 0 ? "" : undefined, }), }), item: slot<{ value: string }, { index: number; count: number; grabbed: boolean }>({ props: { value: "string" }, role: "listitem", state: (state, part) => ({ index: part.api.reorder.order(state).indexOf(part.key), count: state.value.length, grabbed: part.api.reorder.moving(state, part.key), }), attrs: (state, part) => ({ "data-grabbed": part.api.reorder.moving(state, part.key) ? "" : undefined, "data-dragging": part.api.reorder.dragging(state, part.key) ? "" : undefined, }), bind: (el, part) => part.api.reorder.bind(el, part), }), "item-handle": slot<{ value: string }>({ props: { value: { kind: "string", from: "item", required: true } }, attrs: (state, part) => { const index = part.api.reorder.order(state).indexOf(part.key) + 1; return { type: "button", "aria-label": `Reorder ${state.itemLabel} ${index}`, "aria-pressed": String(part.api.reorder.moving(state, part.key)), "aria-disabled": state.disabled ? "true" : undefined, }; }, on: { keydown: (event, { api, key }) => { api.reorder.keydown(event as KeyboardEvent, key); }, pointerdown: (event, { api, key }) => api.reorder.pointerdown(event as PointerEvent, key), }, }), "item-remove": slot<{ value: string }>({ props: { value: { kind: "string", from: "item", required: true } }, attrs: (state, part) => { const index = part.api.reorder.order(state).indexOf(part.key) + 1; return { type: "button", "aria-label": `Remove ${state.itemLabel} ${index}`, "aria-disabled": canRemove(state) ? undefined : "true", }; }, press: ({ api, key }, event) => { api.remove(key, event); }, }), add: slot({ attrs: (state) => ({ type: "button", "aria-disabled": canAdd(state) ? undefined : "true", }), press: ({ api }, event) => { api.add(event); }, }), }), agent: { actions: ["add", "remove"] },});
const Parts = createParts(repeater, { root: "div", list: "div", item: "div", "item-handle": "button", "item-remove": "button", add: "button",});
type PartClassName<T> = Omit<React.ComponentProps<T extends React.ElementType ? T : never>, "className"> & { className?: string;};
// The row's value reaches its handle and remove button from the item around them.type ItemPartProps<T> = Omit<PartClassName<T>, "value"> & { value?: string };
type ButtonStyleProps = Pick<React.ComponentProps<typeof Button>, "variant" | "size">;
function Repeater({ className, ...props }: PartClassName<typeof Parts.Root>) { return ( <Parts.Root className={cn("flex w-full flex-col gap-3 data-disabled:opacity-60", className)} {...props} /> );}
function RepeaterList({ className, ...props }: PartClassName<typeof Parts.List>) { return <Parts.List className={cn("flex flex-col gap-2", className)} {...props} />;}
function RepeaterItem({ className, ...props }: PartClassName<typeof Parts.Item>) { return ( <Parts.Item className={cn( "group/repeater-item relative flex items-start gap-2 rounded-lg transition-[box-shadow,background-color]", "data-grabbed:bg-background data-grabbed:ring-ring/40 data-grabbed:z-10 data-grabbed:shadow-lg data-grabbed:ring-2", "data-dragging:transform-[translate(var(--drag-x,0),var(--drag-y,0))] data-dragging:transition-none", className, )} {...props} /> );}
function RepeaterItemHandle({ className, children, ...props}: ItemPartProps<typeof Parts.ItemHandle>) { return ( <Parts.ItemHandle render={<Button variant="ghost" size="icon" />} className={cn( "text-muted-foreground shrink-0 cursor-grab touch-none active:cursor-grabbing aria-disabled:cursor-not-allowed aria-pressed:bg-accent aria-pressed:text-foreground", className, )} {...(props as PartClassName<typeof Parts.ItemHandle>)} > {children ?? <GripVerticalIcon aria-hidden="true" />} </Parts.ItemHandle> );}
function RepeaterItemRemove({ className, children, ...props}: ItemPartProps<typeof Parts.ItemRemove>) { return ( <Parts.ItemRemove render={<Button variant="ghost" size="icon" />} className={cn( "text-muted-foreground hover:text-destructive shrink-0 aria-disabled:pointer-events-none aria-disabled:opacity-40", className, )} {...(props as PartClassName<typeof Parts.ItemRemove>)} > {children ?? <Trash2Icon aria-hidden="true" />} </Parts.ItemRemove> );}
function RepeaterAdd({ className, children, variant = "outline", size = "sm", ...props}: PartClassName<typeof Parts.Add> & ButtonStyleProps) { return ( <Parts.Add render={<Button variant={variant} size={size} />} className={cn("self-start aria-disabled:pointer-events-none aria-disabled:opacity-50", className)} {...props} > {children ?? ( <> <PlusIcon aria-hidden="true" /> Add item </> )} </Parts.Add> );}
function useRepeaterRows<Row extends { id: string }>( initialRows: Row[], createRow: (id: string) => Row,) { const [rows, setRows] = React.useState(initialRows);
const onValueChange = React.useCallback( (next: string[]) => setRows((current) => { const byId = new Map(current.map((row) => [row.id, row])); return next.map((id) => byId.get(id) ?? createRow(id)); }), [createRow], );
const updateRow = React.useCallback( (id: string, patch: Partial<Row>) => setRows((current) => current.map((row) => (row.id === id ? { ...row, ...patch } : row))), [], );
return { rows, setRows, value: rows.map((row) => row.id), onValueChange, updateRow };}
export { Repeater, RepeaterAdd, RepeaterItem, RepeaterItemHandle, RepeaterItemRemove, RepeaterList, repeater, useRepeaterRows,};export type { RepeaterOptions, RepeaterReason };
Usage
import {
Repeater,
RepeaterAdd,
RepeaterItem,
RepeaterItemHandle,
RepeaterItemRemove,
RepeaterList,
useRepeaterRows,
} from "@/components/ui/repeater";
type Link = { id: string; url: string };
const createLink = (id: string): Link => ({ id, url: "" });
export function SocialLinks() {
const { rows, value, onValueChange, updateRow } = useRepeaterRows<Link>(
[createLink("l1")],
createLink,
);
const byId = new Map(rows.map((row) => [row.id, row]));
return (
<Repeater
aria-label="Social links"
itemLabel="Link"
max={4}
value={value}
onValueChange={onValueChange}
>
<RepeaterList>
{({ order }) =>
order.map((id) => (
<RepeaterItem key={id} value={id}>
{({ index }) => (
<>
<RepeaterItemHandle />
<Input
aria-label={`URL for link ${index + 1}`}
value={byId.get(id)?.url ?? ""}
onChange={(event) =>
updateRow(id, { url: event.target.value })
}
/>
<RepeaterItemRemove />
</>
)}
</RepeaterItem>
))
}
</RepeaterList>
<RepeaterAdd>Add link</RepeaterAdd>
</Repeater>
);
}
How the data works
The repeater's value is an array of row ids, not row data. Keep the data in your own state, keyed by id. useRepeaterRows does this for you:
rowsis your data in the current order.valueandonValueChangego straight toRepeater. A new id fromonValueChangecreates a row with yourcreateRowfunction, and a missing id removes it.updateRow(id, patch)merges a change into one row.setRowsreplaces everything, for example after loading from a server.
Render rows from the order that RepeaterList passes to its children, not from rows. While a row is being dragged, order already shows where it will land.
Examples
Reorder
Add RepeaterItemHandle to a row to make it draggable. It also works with the keyboard.
Min and Max
min disables the remove buttons at that count, and max disables the add button.
Empty
RepeaterList has data-empty when there are no rows, so an empty state can take its place.
No options yet.
Disabled
Complete forms built with Repeater, such as invoice line items, team invites and an FAQ builder, are on the Repeater components page.
API Reference
Repeater
The root. Renders a div with role="group".
| Prop | Type | Default | Description |
|---|---|---|---|
value | string[] | The row ids in order. Pass it to control the repeater. | |
defaultValue | string[] | [] | The row ids at first, when uncontrolled. |
onValueChange | (value, details) => void | Runs when a row is added, removed or moved. details.reason is "add", "remove" or a reorder reason. | |
min | number | 0 | The fewest rows. Remove buttons are disabled at this count. |
max | number | The most rows. The add button is disabled at this count. | |
disabled | boolean | false | Disables adding, removing and reordering. |
itemLabel | string | "Item" | The row name in labels and announcements, like "Remove Link 2" or "Link 3 added". |
createKey | () => string | crypto.randomUUID | Creates the id for a new row. |
className | string | Classes for the root. |
The root has data-disabled while disabled.
RepeaterList
The list of rows, with role="list". Its children can be a function that receives { order }, the row ids in display order. It has data-empty when there are no rows.
RepeaterItem
One row, with role="listitem".
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | The row id. Required. | |
children | ReactNode or (state) => ReactNode | A function receives index, count and grabbed. | |
className | string | Classes for the row. |
A row has data-grabbed while it is picked up and data-dragging while a pointer drags it.
RepeaterItemHandle
The drag handle. A ghost icon Button with a grip icon and the label "Reorder Item 1". Place it inside a RepeaterItem. Pass children to replace the icon.
RepeaterItemRemove
The remove button. A ghost icon Button with a trash icon and the label "Remove Item 1". It is disabled when the row count is at min.
RepeaterAdd
The add button. A Button that accepts variant (default "outline") and size (default "sm"). The default content is a plus icon and "Add item". It is disabled when the row count is at max.
useRepeaterRows
const { rows, setRows, value, onValueChange, updateRow } = useRepeaterRows(
initialRows, // Row[], each with an id
createRow, // (id: string) => Row
);
Pass createRow as a stable function, defined outside the component or wrapped in useCallback.
Keyboard
| Key | Action |
|---|---|
Space, Enter | On a handle, picks the row up. Pressed again, drops it. |
ArrowUp, ArrowDown | Moves the picked up row. |
Home, End | Moves the picked up row to the start or the end. |
Escape | Puts the row back where it was. |
Tab | Puts the row back and moves focus on. |
Accessibility
- Adding, removing and moving rows is announced to screen readers, for example "Link 3 added".
- After adding a row, focus moves to the first field of the new row. After removing one, focus moves to the remove button of the row that took its place, or to the add button.
- The handle, remove and add buttons are labeled with
itemLabeland the row position. - Give each field in a row its own label that includes the row number, for example
aria-label={`Email for invite ${index + 1}`}.
For AI Agents
When to use
- Forms where the user decides how many entries there are: invoice lines, product variants, invitees, links, FAQ entries, key-value pairs.
- Lists the user should be able to reorder by hand.
When not to use
- Reordering items that are not form rows, such as cards or a kanban board. Use Sortable.
- Editing many records with sorting and filtering. Use a data table.
- A fixed number of fields. Render them directly.
Agent notes
- Import from
@/components/ui/repeater. Keep row data inuseRepeaterRowsor your own state keyed by id. The repeater only stores ids. - Always map over
orderfromRepeaterListchildren, and give everyRepeaterItembothkey={id}andvalue={id}. RepeaterItemHandleandRepeaterItemRemovemust be inside aRepeaterItem. They read the row id from it.- Use
itemLabelwith a singular noun, such as "Variant" or "Invite", so labels and announcements read naturally.
Resources
- Markdown: /docs/components/repeater.md
- Variants: Repeater components, 6 free examples
- Install:
npx shadcn@latest add @shadcnuikit/repeater1 - MCP: call
get_item_codewithrepeater1from the MCP Server - Full index for agents: llms.txt