Containment
Sortable list
Drag rows to reorder. The grabbed row lifts; the others slide aside to make room; dropping settles.
Examples and variants
Tasks
Drag the handles, or Space, arrows, Space.
- Write the brief
- Pick the palette
- Build the tokens
- Ship the kit
function SortableTasks() {
const [tasks, setTasks] = useState(["Write the brief", "Pick the palette", "Build the tokens", "Ship the kit"])
return (
<div className="w-full max-w-xs">
<SortableList items={tasks} getKey={(t) => t} getLabel={(t) => t} onReorder={setTasks} renderItem={(t) => <span className="text-sm">{t}</span>} label="Tasks" />
</div>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/sortable-list.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install cn lucide-reactCopy this file to the same paths in your project. Imports use the
@/alias for your project root.components/ui/sortable-list.tsxsortable-list
components/ui/sortable-list.tsx"use client" import * as React from "react" import { GripVerticalIcon } from "lucide-react" import { cn } from "cn" import { tokenMs } from "@/lib/motion/token-ms" import { motionLevel } from "@/lib/overlay" /* Sortable list: drag rows to reorder. The grabbed row lifts; the others slide aside (FLIP) to make room; dropping settles with a small bounce. Keyboard: focus a handle, Space to pick up, arrows to move, Space to drop, Escape to cancel. Every move is announced. */ function SortableList<T>({ items, getKey, getLabel, renderItem, onReorder, label = "Reorder items", className, }: { items: T[] getKey: (item: T) => string | number getLabel: (item: T) => string renderItem: (item: T) => React.ReactNode onReorder: (items: T[]) => void label?: string className?: string }) { const listRef = React.useRef<HTMLUListElement>(null) const places = React.useRef(new Map<string | number, number>()) const [dragKey, setDragKey] = React.useState<string | number | null>(null) const [offset, setOffset] = React.useState(0) const [picked, setPicked] = React.useState<string | number | null>(null) const [announce, setAnnounce] = React.useState("") const startY = React.useRef(0) const startIndex = React.useRef(0) const original = React.useRef<T[] | null>(null) // The latest order, updated immediately on each move so fast drags never // compute from an order that hasn't re-rendered yet. const current = React.useRef(items) React.useEffect(() => { current.current = items }, [items]) // FLIP: every row except the dragged one slides from its old place. React.useLayoutEffect(() => { const list = listRef.current if (!list) return const level = motionLevel(list) const next = new Map<string | number, number>() list.querySelectorAll<HTMLElement>("[data-sortable-key]").forEach((row) => { const key = row.dataset.sortableKey! const top = row.offsetTop const before = places.current.get(key) next.set(key, top) if (level === "still" || before === undefined || key === String(dragKey) || Math.abs(before - top) < 1) return row.animate([{ transform: `translateY(${before - top}px)` }, { transform: "none" }], { duration: tokenMs("--duration-fast", list), easing: getComputedStyle(list).getPropertyValue("--ease-out").trim() || "ease", }) }) places.current = next }) function indexOf(key: string | number) { return current.current.findIndex((item) => getKey(item) === key) } function move(key: string | number, to: number) { const list = current.current const from = indexOf(key) const target = Math.max(0, Math.min(list.length - 1, to)) if (from === -1 || target === from) return false const next = [...list] const [item] = next.splice(from, 1) next.splice(target, 0, item) current.current = next onReorder(next) return true } return ( <> <ul ref={listRef} aria-label={label} data-slot="sortable-list" className={cn("relative flex w-full flex-col gap-(--sortable-gap)", className)}> {items.map((item, index) => { const key = getKey(item) const dragging = dragKey === key return ( <li key={key} data-sortable-key={String(key)} data-dragging={dragging || undefined} data-picked={picked === key || undefined} className="sortable-row relative flex items-center gap-inline-sm rounded-(--sortable-corner) bg-(--sortable-container) py-(--space-inset-item-y) ps-1 pe-3 shadow-(--sortable-elevation)" style={dragging ? { transform: `translateY(${offset}px)`, zIndex: 10 } : undefined} > <button type="button" aria-label={`Reorder ${getLabel(item)}`} aria-pressed={picked === key} className="inline-flex size-(--size-control-sm) shrink-0 cursor-grab touch-none items-center justify-center rounded-(--shape-sm) text-ink-subtle outline-none hover:bg-(--sortable-handle-container-hover) active:bg-(--sortable-handle-container-pressed) focus-visible:shadow-(--focus-ring) active:cursor-grabbing [&_svg]:size-(--size-icon-md)" onPointerDown={(event) => { try { event.currentTarget.setPointerCapture(event.pointerId) } catch {} startY.current = event.clientY startIndex.current = indexOf(key) setDragKey(key) setOffset(0) }} onPointerMove={(event) => { if (dragKey !== key || !listRef.current) return const row = event.currentTarget.parentElement as HTMLElement const pitch = row.offsetHeight + parseFloat(getComputedStyle(listRef.current).rowGap || "0") const dy = event.clientY - startY.current move(key, startIndex.current + Math.round(dy / pitch)) setOffset(dy - (indexOf(key) - startIndex.current) * pitch) }} onPointerUp={() => { setDragKey(null) setOffset(0) setAnnounce(`${getLabel(item)} dropped at position ${indexOf(key) + 1} of ${items.length}`) }} onKeyDown={(event) => { if (event.key === " " || event.key === "Enter") { event.preventDefault() if (picked === key) { setPicked(null) original.current = null setAnnounce(`${getLabel(item)} dropped at position ${index + 1} of ${items.length}`) } else { setPicked(key) original.current = items setAnnounce(`${getLabel(item)} picked up. Use the arrow keys to move, Space to drop, Escape to cancel.`) } } else if (picked === key && (event.key === "ArrowUp" || event.key === "ArrowDown")) { event.preventDefault() const to = indexOf(key) + (event.key === "ArrowUp" ? -1 : 1) if (move(key, to)) setAnnounce(`${getLabel(item)} moved to position ${to + 1} of ${items.length}`) requestAnimationFrame(() => (listRef.current?.querySelector(`[data-sortable-key="${key}"] button`) as HTMLElement | null)?.focus()) } else if (picked === key && event.key === "Escape") { if (original.current) { current.current = original.current onReorder(original.current) } setPicked(null) setAnnounce("Reorder cancelled") } }} > <GripVerticalIcon aria-hidden /> </button> <div className="min-w-0 flex-1">{renderItem(item)}</div> </li> ) })} </ul> <p role="status" aria-live="assertive" className="sr-only"> {announce} </p> </> ) } export { SortableList }
Imports
What the examples on this page import:
import { Badge } from "@/components/ui/badge"
import { PagePeel } from "@/components/ui/page-peel"
import { PullToRefresh } from "@/components/ui/pull-to-refresh"
import { SignaturePad } from "@/components/ui/signature-pad"
import { SortableList } from "@/components/ui/sortable-list"
import { SwipeDeck } from "@/components/ui/swipe-deck"
import { tokenMs } from "@/lib/motion/token-ms"Anatomy
- 1Row · --sortable-container, --sortable-corner, --sortable-elevation; lifted --sortable-elevation-lifted.
- 2Handle · The drag and keyboard target.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items, getKey, getLabel, renderItem | T[] and functions | — | Rows. |
onReorder | (items: T[]) => void | — | Called with the new order. |
label | string | — | List name. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--sortable-gap | var(--space-2) | 8px | same |
--sortable-corner | var(--shape-md) | 14px | same |
--sortable-handle-container-hover | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--sortable-handle-container-pressed | var(--color-bg-pressed) | oklch(0.94 0.007 95) | oklch(0.27 0 0) |
--sortable-container | var(--surface-container-lowest) | oklch(1 0 0) | oklch(0.14 0 0) |
--sortable-elevation | var(--elevation-1) | 0 1px 1px -0.5px oklch(0.22 0.01 260 / 7%), 0 2px 3px -1px oklch(0.22 0.01 260 / 10%), 0 4px 8px -4px oklch(0.22 0.01 260 / 6%) | 0 1px 2px oklch(0 0 0 / 35%), 0 2px 10px oklch(0 0 0 / 25%) |
--sortable-elevation-lifted | var(--elevation-4) | 0 2.8px 2.2px oklch(0.22 0.01 260 / 3.4%), 0 6.7px 5.3px oklch(0.22 0.01 260 / 4.8%), 0 12.5px 10px oklch(0.22 0.01 260 / 6%), 0 22.3px 17.9px oklch(0.22 0.01 260 / 7.2%), 0 41.8px 33.4px oklch(0.22 0.01 260 / 8.6%), 0 100px 80px oklch(0.22 0.01 260 / 12%) | 0 12px 24px oklch(0 0 0 / 50%), 0 28px 56px oklch(0 0 0 / 45%) |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Drag | Row lifts; neighbours slide (FLIP); drop settles. | --duration-fast |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- Space picks up, arrows move, Space drops, Escape cancels; every move is announced.
Usage
Do
- Use for short, user-ordered lists.
Don’t
- Don't use for sorted data (use Table sorting).
Code
"use client"
import * as React from "react"
import { GripVerticalIcon } from "lucide-react"
import { cn } from "cn"
import { tokenMs } from "@/lib/motion/token-ms"
import { motionLevel } from "@/lib/overlay"
/*
Sortable list: drag rows to reorder. The grabbed row lifts; the others
slide aside (FLIP) to make room; dropping settles with a small bounce.
Keyboard: focus a handle, Space to pick up, arrows to move, Space to drop,
Escape to cancel. Every move is announced.
*/
function SortableList<T>({
items,
getKey,
getLabel,
renderItem,
onReorder,
label = "Reorder items",
className,
}: {
items: T[]
getKey: (item: T) => string | number
getLabel: (item: T) => string
renderItem: (item: T) => React.ReactNode
onReorder: (items: T[]) => void
label?: string
className?: string
}) {
const listRef = React.useRef<HTMLUListElement>(null)
const places = React.useRef(new Map<string | number, number>())
const [dragKey, setDragKey] = React.useState<string | number | null>(null)
const [offset, setOffset] = React.useState(0)
const [picked, setPicked] = React.useState<string | number | null>(null)
const [announce, setAnnounce] = React.useState("")
const startY = React.useRef(0)
const startIndex = React.useRef(0)
const original = React.useRef<T[] | null>(null)
// The latest order, updated immediately on each move so fast drags never
// compute from an order that hasn't re-rendered yet.
const current = React.useRef(items)
React.useEffect(() => {
current.current = items
}, [items])
// FLIP: every row except the dragged one slides from its old place.
React.useLayoutEffect(() => {
const list = listRef.current
if (!list) return
const level = motionLevel(list)
const next = new Map<string | number, number>()
list.querySelectorAll<HTMLElement>("[data-sortable-key]").forEach((row) => {
const key = row.dataset.sortableKey!
const top = row.offsetTop
const before = places.current.get(key)
next.set(key, top)
if (level === "still" || before === undefined || key === String(dragKey) || Math.abs(before - top) < 1) return
row.animate([{ transform: `translateY(${before - top}px)` }, { transform: "none" }], {
duration: tokenMs("--duration-fast", list),
easing: getComputedStyle(list).getPropertyValue("--ease-out").trim() || "ease",
})
})
places.current = next
})
function indexOf(key: string | number) {
return current.current.findIndex((item) => getKey(item) === key)
}
function move(key: string | number, to: number) {
const list = current.current
const from = indexOf(key)
const target = Math.max(0, Math.min(list.length - 1, to))
if (from === -1 || target === from) return false
const next = [...list]
const [item] = next.splice(from, 1)
next.splice(target, 0, item)
current.current = next
onReorder(next)
return true
}
return (
<>
<ul ref={listRef} aria-label={label} data-slot="sortable-list" className={cn("relative flex w-full flex-col gap-(--sortable-gap)", className)}>
{items.map((item, index) => {
const key = getKey(item)
const dragging = dragKey === key
return (
<li
key={key}
data-sortable-key={String(key)}
data-dragging={dragging || undefined}
data-picked={picked === key || undefined}
className="sortable-row relative flex items-center gap-inline-sm rounded-(--sortable-corner) bg-(--sortable-container) py-(--space-inset-item-y) ps-1 pe-3 shadow-(--sortable-elevation)"
style={dragging ? { transform: `translateY(${offset}px)`, zIndex: 10 } : undefined}
>
<button
type="button"
aria-label={`Reorder ${getLabel(item)}`}
aria-pressed={picked === key}
className="inline-flex size-(--size-control-sm) shrink-0 cursor-grab touch-none items-center justify-center rounded-(--shape-sm) text-ink-subtle outline-none hover:bg-(--sortable-handle-container-hover) active:bg-(--sortable-handle-container-pressed) focus-visible:shadow-(--focus-ring) active:cursor-grabbing [&_svg]:size-(--size-icon-md)"
onPointerDown={(event) => {
try {
event.currentTarget.setPointerCapture(event.pointerId)
} catch {}
startY.current = event.clientY
startIndex.current = indexOf(key)
setDragKey(key)
setOffset(0)
}}
onPointerMove={(event) => {
if (dragKey !== key || !listRef.current) return
const row = event.currentTarget.parentElement as HTMLElement
const pitch = row.offsetHeight + parseFloat(getComputedStyle(listRef.current).rowGap || "0")
const dy = event.clientY - startY.current
move(key, startIndex.current + Math.round(dy / pitch))
setOffset(dy - (indexOf(key) - startIndex.current) * pitch)
}}
onPointerUp={() => {
setDragKey(null)
setOffset(0)
setAnnounce(`${getLabel(item)} dropped at position ${indexOf(key) + 1} of ${items.length}`)
}}
onKeyDown={(event) => {
if (event.key === " " || event.key === "Enter") {
event.preventDefault()
if (picked === key) {
setPicked(null)
original.current = null
setAnnounce(`${getLabel(item)} dropped at position ${index + 1} of ${items.length}`)
} else {
setPicked(key)
original.current = items
setAnnounce(`${getLabel(item)} picked up. Use the arrow keys to move, Space to drop, Escape to cancel.`)
}
} else if (picked === key && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
event.preventDefault()
const to = indexOf(key) + (event.key === "ArrowUp" ? -1 : 1)
if (move(key, to)) setAnnounce(`${getLabel(item)} moved to position ${to + 1} of ${items.length}`)
requestAnimationFrame(() => (listRef.current?.querySelector(`[data-sortable-key="${key}"] button`) as HTMLElement | null)?.focus())
} else if (picked === key && event.key === "Escape") {
if (original.current) {
current.current = original.current
onReorder(original.current)
}
setPicked(null)
setAnnounce("Reorder cancelled")
}
}}
>
<GripVerticalIcon aria-hidden />
</button>
<div className="min-w-0 flex-1">{renderItem(item)}</div>
</li>
)
})}
</ul>
<p role="status" aria-live="assertive" className="sr-only">
{announce}
</p>
</>
)
}
export { SortableList }