//data
Sortable
Drag-and-drop reordering for lists, rows, grids and Kanban boards, with keyboard support, built on dnd-kit. Copy-paste ready.
// title: Task list with drag handles
"use client";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import {
Sortable,
SortableItem,
SortableItemHandle,
} from "@/components/ui/sortable";
type Task = {
id: string;
title: string;
done: boolean;
label: "Bug" | "Feature" | "Docs";
};
const LABELS = {
Bug: "error",
Docs: "secondary",
Feature: "info",
} as const;
const initial: Task[] = [
{ done: false, id: "t1", label: "Bug", title: "Fix focus ring on Select" },
{ done: true, id: "t2", label: "Feature", title: "Add Stepper component" },
{ done: false, id: "t3", label: "Docs", title: "Document Tag Input props" },
{ done: false, id: "t4", label: "Feature", title: "Ship File Upload" },
{ done: false, id: "t5", label: "Bug", title: "Toast stacks off-screen" },
];
export default function Particle() {
const [tasks, setTasks] = useState(initial);
return (
<div className="w-full max-w-md">
<div className="mb-2 flex items-baseline justify-between">
<p className="font-medium text-sm">Sprint backlog</p>
<p className="text-muted-foreground text-xs">
Drag the handle, or focus it and use Space + arrow keys
</p>
</div>
<Sortable
getItemValue={(t) => t.id}
onValueChange={setTasks}
value={tasks}
>
<div className="flex flex-col gap-1.5">
{tasks.map((task) => (
<SortableItem
className="flex items-center gap-3 rounded-lg border bg-background px-2 py-2"
key={task.id}
value={task.id}
>
<SortableItemHandle className="size-6" />
<Checkbox
aria-label={task.title}
checked={task.done}
onCheckedChange={(done) =>
setTasks((all) =>
all.map((t) =>
t.id === task.id ? { ...t, done: !!done } : t,
),
)
}
/>
<span
className={
task.done
? "flex-1 truncate text-muted-foreground text-sm line-through"
: "flex-1 truncate text-sm"
}
>
{task.title}
</span>
<Badge variant={LABELS[task.label]}>{task.label}</Badge>
</SortableItem>
))}
</div>
</Sortable>
</div>
);
}
Installation
pnpm dlx shadcn@latest add @cnippet/sortable
Usage
import {
Sortable,
SortableItem,
SortableItemHandle,
} from "@/components/ui/sortable"const [tasks, setTasks] = useState(initialTasks)
<Sortable value={tasks} onValueChange={setTasks} getItemValue={(t) => t.id}>
{tasks.map((task) => (
<SortableItem key={task.id} value={task.id} className="flex items-center gap-2">
<SortableItemHandle />
{task.title}
</SortableItem>
))}
</Sortable>Anatomy
<Sortable> {/* drag context; calls onValueChange with the reordered array */}
<SortableItem value={id}> {/* one draggable item; data-dragging while it moves */}
<SortableItemHandle /> {/* the grip that starts a drag; leave it out and use asHandle instead */}
</SortableItem>
</Sortable>Good to know
Sortabledoesn't render any element, so wrap the items in your own list, row or grid and matchorientationto it:"vertical","horizontal"or"grid".getItemValuemust return a unique, stable id. Don't use the array index; it changes as items move.- Keyboard users focus a handle (or an
asHandleitem), press Space to pick it up, move it with the arrow keys, and press Space again to drop it or Escape to cancel. dnd-kit announces each step to screen readers. - A drag only starts after the pointer moves 4px, so clicks on buttons and checkboxes inside an item still work.
SortableItemandSortableItemHandlework under any dnd-kitSortableContext. For drags between lists, like the Kanban example, use your ownDndContextwithuseSortableSensors()and oneSortableContextper list.
API Reference
Sortable
| Prop | Type | Default | Description |
|---|---|---|---|
value | T[] | — | The items, in order |
onValueChange | (value: T[]) => void | — | Called with the reordered items after a drop |
getItemValue | (item: T) => UniqueIdentifier | — | A unique id for each item |
orientation | "vertical" | "horizontal" | "grid" | "vertical" | How the items are laid out |
SortableItem
| Prop | Type | Default | Description |
|---|---|---|---|
value | UniqueIdentifier | — | This item's id, matching getItemValue |
asHandle | boolean | false | Make the whole item draggable |
disabled | boolean | false | Keep this item in place |
Renders a <div>; other props go on it.
SortableItemHandle
A <button> that starts the drag, with a grip icon unless you pass children. Its label is "Drag to reorder".
Helpers
useSortableSensors() returns the pointer and keyboard sensors Sortable uses, for your own DndContext. arrayMove is re-exported from dnd-kit.
Examples
Ranking
The whole row is the handle, and the rank numbers update as items move.
// title: Drag-to-rank list
"use client";
import { useState } from "react";
import { Sortable, SortableItem } from "@/components/ui/sortable";
const initial = [
"Faster page loads",
"Dark mode for email",
"Better search",
"Offline support",
"Two-factor login",
];
export default function Particle() {
const [items, setItems] = useState(initial);
return (
<div className="w-full max-w-xs">
<p className="font-medium text-sm">Rank what matters most</p>
<p className="mb-3 text-muted-foreground text-xs">
Drag to reorder. #1 is your top pick.
</p>
<Sortable getItemValue={(i) => i} onValueChange={setItems} value={items}>
<ol className="flex flex-col gap-1.5">
{items.map((item, index) => (
<li key={item}>
<SortableItem
asHandle
className="flex items-center gap-3 rounded-lg border bg-background px-3 py-2 text-sm"
value={item}
>
<span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-accent font-medium text-xs tabular-nums">
{index + 1}
</span>
{item}
</SortableItem>
</li>
))}
</ol>
</Sortable>
</div>
);
}
Horizontal
Reorder shortcut tabs in a row.
// title: Horizontal shortcut tabs
"use client";
import {
BarChart3Icon,
HomeIcon,
InboxIcon,
type LucideIcon,
SettingsIcon,
UsersIcon,
} from "lucide-react";
import { useState } from "react";
import { Sortable, SortableItem } from "@/components/ui/sortable";
type Tab = { id: string; label: string; icon: LucideIcon };
const initial: Tab[] = [
{ icon: HomeIcon, id: "home", label: "Home" },
{ icon: InboxIcon, id: "inbox", label: "Inbox" },
{ icon: BarChart3Icon, id: "reports", label: "Reports" },
{ icon: UsersIcon, id: "team", label: "Team" },
{ icon: SettingsIcon, id: "settings", label: "Settings" },
];
export default function Particle() {
const [tabs, setTabs] = useState(initial);
return (
<div className="flex flex-col items-center gap-3">
<Sortable
getItemValue={(t) => t.id}
onValueChange={setTabs}
orientation="horizontal"
value={tabs}
>
<div className="flex gap-1 rounded-xl border bg-muted/40 p-1">
{tabs.map((tab) => (
<SortableItem
asHandle
className="flex items-center gap-1.5 rounded-lg bg-background px-3 py-1.5 font-medium text-sm shadow-xs/5"
key={tab.id}
value={tab.id}
>
<tab.icon aria-hidden="true" className="size-4 opacity-72" />
{tab.label}
</SortableItem>
))}
</div>
</Sortable>
<p className="text-muted-foreground text-xs">
Drag the shortcuts into the order you use them.
</p>
</div>
);
}
Grid
Rearrange dashboard cards in a responsive grid by their handles.
// title: Dashboard widget grid
"use client";
import { useState } from "react";
import {
Sortable,
SortableItem,
SortableItemHandle,
} from "@/components/ui/sortable";
type Widget = { id: string; label: string; value: string; delta: string };
const initial: Widget[] = [
{ delta: "+12%", id: "revenue", label: "Revenue", value: "$48.2k" },
{ delta: "+4%", id: "users", label: "Active users", value: "2,814" },
{ delta: "-2%", id: "churn", label: "Churn", value: "1.9%" },
{ delta: "+8%", id: "orders", label: "Orders", value: "1,206" },
{ delta: "+1%", id: "nps", label: "NPS", value: "62" },
{ delta: "-5%", id: "tickets", label: "Open tickets", value: "37" },
];
export default function Particle() {
const [widgets, setWidgets] = useState(initial);
return (
<div className="w-full max-w-lg">
<p className="mb-3 text-muted-foreground text-xs">
Rearrange your dashboard by dragging a card's handle.
</p>
<Sortable
getItemValue={(w) => w.id}
onValueChange={setWidgets}
orientation="grid"
value={widgets}
>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{widgets.map((w) => (
<SortableItem
className="rounded-xl border bg-background p-3"
key={w.id}
value={w.id}
>
<div className="flex items-start justify-between gap-2">
<p className="text-muted-foreground text-xs">{w.label}</p>
<SortableItemHandle className="-me-1 -mt-1 size-6" />
</div>
<p className="mt-1 font-semibold text-lg tabular-nums">
{w.value}
</p>
<p
className={
w.delta.startsWith("-")
? "text-destructive-foreground text-xs"
: "text-success-foreground text-xs"
}
>
{w.delta} vs last month
</p>
</SortableItem>
))}
</div>
</Sortable>
</div>
);
}
Kanban
Move cards within and between columns, including into an empty one.
// title: Kanban board with cross-column moves
"use client";
import {
closestCorners,
DndContext,
type DragOverEvent,
type UniqueIdentifier,
useDroppable,
} from "@dnd-kit/core";
import {
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { useState } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
arrayMove,
SortableItem,
useSortableSensors,
} from "@/components/ui/sortable";
type Card = { id: string; title: string; owner: string };
type ColumnId = "todo" | "doing" | "done";
const COLUMNS: { id: ColumnId; title: string }[] = [
{ id: "todo", title: "To do" },
{ id: "doing", title: "In progress" },
{ id: "done", title: "Done" },
];
const initial: Record<ColumnId, Card[]> = {
doing: [
{ id: "c3", owner: "JL", title: "Stepper keyboard support" },
{ id: "c4", owner: "MP", title: "Tag Input docs" },
],
done: [{ id: "c5", owner: "SK", title: "File Upload dropzone" }],
todo: [
{ id: "c1", owner: "MP", title: "Color picker spike" },
{ id: "c2", owner: "SK", title: "Audit chart tokens" },
],
};
function findColumn(
board: Record<ColumnId, Card[]>,
id: UniqueIdentifier,
): ColumnId | undefined {
if (id in board) return id as ColumnId;
return COLUMNS.find((c) => board[c.id].some((card) => card.id === id))?.id;
}
function Column({
id,
title,
cards,
}: {
id: ColumnId;
title: string;
cards: Card[];
}) {
// Lets cards drop into an empty column.
const { setNodeRef } = useDroppable({ id });
return (
<div className="flex min-w-0 flex-col gap-2 rounded-xl bg-muted/40 p-2">
<p className="flex items-center justify-between px-1 font-medium text-xs">
{title}
<span className="text-muted-foreground tabular-nums">
{cards.length}
</span>
</p>
<SortableContext
id={id}
items={cards.map((c) => c.id)}
strategy={verticalListSortingStrategy}
>
<div className="flex min-h-24 flex-col gap-2" ref={setNodeRef}>
{cards.map((card) => (
<SortableItem
asHandle
className="flex flex-col gap-2 rounded-lg border bg-background p-2.5 text-sm"
key={card.id}
value={card.id}
>
{card.title}
<Avatar className="size-5 self-end">
<AvatarFallback className="text-[10px]">
{card.owner}
</AvatarFallback>
</Avatar>
</SortableItem>
))}
</div>
</SortableContext>
</div>
);
}
export default function Particle() {
const [board, setBoard] = useState(initial);
const sensors = useSortableSensors();
// Moves the card into whichever column or card it's over, live while dragging.
const handleDragOver = ({ active, over }: DragOverEvent) => {
if (!over) return;
const from = findColumn(board, active.id);
const to = findColumn(board, over.id);
if (!from || !to) return;
setBoard((prev) => {
const source = prev[from];
const target = prev[to];
const fromIndex = source.findIndex((c) => c.id === active.id);
const card = source[fromIndex];
if (!card) return prev;
if (from === to) {
const toIndex = target.findIndex((c) => c.id === over.id);
if (toIndex === -1 || toIndex === fromIndex) return prev;
return { ...prev, [to]: arrayMove(target, fromIndex, toIndex) };
}
const overIndex = target.findIndex((c) => c.id === over.id);
const insertAt = overIndex === -1 ? target.length : overIndex;
return {
...prev,
[from]: source.filter((c) => c.id !== active.id),
[to]: [...target.slice(0, insertAt), card, ...target.slice(insertAt)],
};
});
};
return (
<DndContext
collisionDetection={closestCorners}
onDragOver={handleDragOver}
sensors={sensors}
>
<div className="grid w-full max-w-2xl grid-cols-3 gap-2 max-sm:grid-cols-1">
{COLUMNS.map((col) => (
<Column
cards={board[col.id]}
id={col.id}
key={col.id}
title={col.title}
/>
))}
</div>
</DndContext>
);
}