Card Stack
A swipeable card stack for React: drag the top card left or right (or use the buttons and arrow keys) and the cards behind spring forward to take its place. Loops or ends, reports every swipe with its direction, and works for testimonials, onboarding, voting and Tinder-style decks.
- Swipe to dismiss
- Buttons & arrow keys
- Loop or finite
- onSwipe callback
- Spring physics
- Reduced-motion crossfade
We replaced three carousel libraries with this. Swiping feels native on every phone we tested.
Card 1 of 5
"use client";
import { Quote } from "lucide-react";
import { CardStack } from "@/components/dusk/card-stack/card-stack";
const testimonials = [
{ name: "Ava Chen", role: "Design lead, Northwind", quote: "We replaced three carousel libraries with this. Swiping feels native on every phone we tested." },
{ name: "Marcus Webb", role: "Founder, Lumen", quote: "The springs are tuned so well that our onboarding finally feels as polished as the product." },
{ name: "Priya Raman", role: "Staff engineer, Orbit", quote: "Keyboard support and the live announcements made our accessibility review a non-event." },
{ name: "Jonas Berg", role: "PM, Fjord", quote: "Drop it in, pass an array, done. It handled our 200-card deck without breaking a sweat." },
{ name: "Lea Martin", role: "Indie developer", quote: "Reduced motion turns it into a calm crossfade. My users with vestibular issues noticed." },
];
export default function CardStackDemo() {
return (
<div className="flex w-full justify-center rounded-xl border border-white/10 bg-background px-6 py-10">
<CardStack
items={testimonials}
getKey={(t) => t.name}
label="Testimonials"
cardClassName="p-6"
renderItem={(t) => (
<figure className="flex h-52 flex-col">
<Quote aria-hidden className="size-5 text-white/30" />
<blockquote className="mt-3 flex-1 text-[15px] leading-relaxed text-white/80">{t.quote}</blockquote>
<figcaption className="mt-4 flex items-center gap-3">
<span
aria-hidden
className="flex size-9 items-center justify-center rounded-full bg-white/10 text-sm font-semibold text-foreground"
>
{t.name.split(" ").map((n) => n[0]).join("")}
</span>
<span>
<span className="block text-sm font-medium text-white">{t.name}</span>
<span className="block text-xs text-white/50">{t.role}</span>
</span>
</figcaption>
</figure>
)}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/card-stack.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/card-stack/card-stack.tsx.card-stack.tsx "use client"; import * as React from "react"; import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useTransform, type PanInfo, } from "motion/react"; import { ArrowLeft, ArrowRight } from "lucide-react"; import { cn } from "@/lib/utils"; export type SwipeDirection = "left" | "right"; export interface CardStackProps<T> extends Omit<React.ComponentProps<"div">, "children" | "onChange"> { /** The data for each card. */ items: T[]; /** Renders the content of one card. */ renderItem: (item: T, index: number) => React.ReactNode; /** Stable key for an item. Defaults to its index. */ getKey?: (item: T, index: number) => React.Key; /** Start over from the first card after the last one. */ loop?: boolean; /** How many cards are visible in the stack. */ visible?: number; /** How far each card behind peeks out below the one in front, in px. */ offset?: number; /** How much smaller each card behind is, from 0 to 1. */ scaleStep?: number; /** Drag distance in px that counts as a swipe. A fast flick also counts. */ threshold?: number; /** Let people drag the top card away. */ draggable?: boolean; /** Show the swipe left / swipe right buttons. */ controls?: boolean; /** Called when a card leaves the stack. */ onSwipe?: (direction: SwipeDirection, item: T, index: number) => void; /** Called once the last card has gone (only when `loop` is off). */ onEnd?: () => void; /** Shown when every card has been swiped (only when `loop` is off). */ empty?: React.ReactNode; /** Accessible labels for the buttons. */ labels?: { left?: string; right?: string }; /** Accessible name of the stack. */ label?: string; /** Classes for every card. */ cardClassName?: string; } type Exit = { direction: 1 | -1; distance: number; reduce: boolean }; const spring = { type: "spring", stiffness: 320, damping: 30, mass: 0.8 } as const; const fade = { duration: 0.2, ease: "easeOut" } as const; /** Reduced motion: cards snap into place and only the opacity crossfades. */ const crossfade = { default: { duration: 0 }, opacity: fade } as const; function StackCard({ depth, offset, scaleStep, draggable, threshold, reduce, onSwipe, className, children, label, }: { depth: number; offset: number; scaleStep: number; draggable: boolean; threshold: number; reduce: boolean; onSwipe: (direction: 1 | -1, distance: number) => void; className?: string; children: React.ReactNode; label: string; }) { const ref = React.useRef<HTMLDivElement>(null); const x = useMotionValue(0); const rotate = useTransform(x, [-240, 0, 240], [-14, 0, 14]); const isTop = depth === 0; const handleDragEnd = (_: unknown, info: PanInfo) => { const swiped = Math.abs(info.offset.x) > threshold || Math.abs(info.velocity.x) > 600; if (swiped) { const direction = (info.offset.x || info.velocity.x) > 0 ? 1 : -1; onSwipe(direction, (ref.current?.offsetWidth ?? 320) + 160); } else { animate(x, 0, reduce ? { duration: 0 } : spring); } }; return ( <motion.div ref={ref} role="group" aria-roledescription="card" aria-label={label} aria-hidden={!isTop || undefined} inert={!isTop || undefined} data-slot="card-stack-card" className={cn( "relative [grid-area:1/1] rounded-xl border border-white/10 bg-card shadow-lg shadow-black/30 outline-none", isTop && draggable && "cursor-grab touch-pan-y active:cursor-grabbing", className )} style={{ x, rotate: reduce ? 0 : rotate, transformOrigin: "50% 100%" }} initial={reduce ? { opacity: 0 } : { opacity: 0, y: (depth + 1) * offset, scale: 1 - (depth + 1) * scaleStep }} animate={ reduce ? { opacity: 1, y: depth * offset, scale: 1 - depth * scaleStep, transition: crossfade } : { opacity: 1, y: depth * offset, scale: 1 - depth * scaleStep, transition: spring } } variants={{ exit: (exit: Exit) => exit.reduce ? { opacity: 0, transition: fade } : { x: exit.direction * exit.distance, rotate: exit.direction * 18, opacity: 0, transition: { ...spring, opacity: { duration: 0.3, delay: 0.1 } }, }, }} exit="exit" drag={isTop && draggable ? "x" : false} dragMomentum={false} onDragEnd={handleDragEnd} > {children} </motion.div> ); } /** A stack of cards where the top one can be swiped left or right, by drag, buttons or arrow keys, while the rest spring forward. */ export function CardStack<T>({ items, renderItem, getKey, loop = true, visible = 3, offset = 14, scaleStep = 0.05, threshold = 100, draggable = true, controls = true, onSwipe, onEnd, empty, labels, label = "Card stack", cardClassName, className, onKeyDown, ...props }: CardStackProps<T>) { const reduce = useReducedMotion() ?? false; const [state, setState] = React.useState<{ position: number; exit: Exit }>({ position: 0, exit: { direction: 1, distance: 480, reduce: false }, }); const count = items.length; const { position } = state; const finished = !loop && position >= count; const depth = Math.max(1, Math.round(visible)); // `position` only grows, so each card keeps one React identity while it moves forward. const cards: { slot: number; index: number; item: T }[] = []; if (count > 0) { for (let i = depth - 1; i >= 0; i--) { const slot = position + i; if (!loop && slot >= count) continue; const index = slot % count; cards.push({ slot, index, item: items[index] }); } } const swipe = (direction: 1 | -1, distance = 480) => { if (count === 0 || finished) return; const index = position % count; setState({ position: position + 1, exit: { direction, distance, reduce } }); onSwipe?.(direction > 0 ? "right" : "left", items[index], index); if (!loop && position + 1 >= count) onEnd?.(); }; const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { onKeyDown?.(event); if (event.defaultPrevented) return; if (event.key === "ArrowLeft") swipe(-1); else if (event.key === "ArrowRight") swipe(1); else return; event.preventDefault(); }; const current = count ? (position % count) + 1 : 0; const status = finished ? "No more cards" : `Card ${current} of ${count}`; const leftLabel = labels?.left ?? "Swipe left"; const rightLabel = labels?.right ?? "Swipe right"; return ( <div data-slot="card-stack" role="region" aria-roledescription="card stack" aria-label={label} aria-keyshortcuts="ArrowLeft ArrowRight" tabIndex={0} className={cn( "group/stack flex w-full max-w-sm flex-col items-center gap-6 rounded-2xl outline-none", "focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-background", className )} onKeyDown={handleKeyDown} {...props} > <div className="grid w-full" // Room for the cards peeking out below, so the stack never changes height. style={{ paddingBottom: (depth - 1) * offset }} > <AnimatePresence initial={false} custom={state.exit}> {cards.map(({ slot, index, item }) => { const d = slot - position; return ( <StackCard key={`${slot}-${getKey ? getKey(item, index) : index}`} depth={d} offset={offset} scaleStep={scaleStep} draggable={draggable} threshold={threshold} reduce={reduce} onSwipe={swipe} className={cardClassName} label={`${index + 1} of ${count}`} > {renderItem(item, index)} </StackCard> ); })} </AnimatePresence> {(finished || count === 0) && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1, transition: { delay: 0.15 } }} className="flex min-h-40 items-center justify-center rounded-xl border border-dashed border-white/10 p-6 text-center text-sm text-muted-foreground [grid-area:1/1]" > {empty ?? "No more cards"} </motion.div> )} </div> {controls && ( <div className="flex items-center gap-4"> <StackButton label={leftLabel} disabled={finished || count === 0} onClick={() => swipe(-1)}> <ArrowLeft /> </StackButton> <span aria-hidden className="min-w-14 text-center font-mono text-xs tabular-nums text-muted-foreground"> {finished ? `${count}/${count}` : `${current}/${count}`} </span> <StackButton label={rightLabel} disabled={finished || count === 0} onClick={() => swipe(1)}> <ArrowRight /> </StackButton> </div> )} <p className="sr-only" aria-live="polite" aria-atomic> {status} </p> </div> ); } function StackButton({ label, disabled, onClick, children, }: { label: string; disabled: boolean; onClick: () => void; children: React.ReactNode; }) { return ( <button type="button" aria-label={label} aria-disabled={disabled || undefined} onClick={() => { if (!disabled) onClick(); }} className={cn( "inline-flex size-11 items-center justify-center rounded-full border border-white/10 bg-card text-foreground outline-none", "transition-[color,background-color,border-color,transform] duration-150 hover:border-white/20 hover:bg-white/[0.04] hover:text-foreground active:scale-[0.97]", "focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none motion-reduce:active:scale-100", "aria-disabled:cursor-not-allowed aria-disabled:opacity-40 aria-disabled:hover:border-white/10 aria-disabled:hover:text-foreground", "[&_svg]:size-4" )} > {children} </button> ); }
Cards are stacked in a CSS grid, so the stack takes the height of its tallest card plus the peek, and never jumps as cards change. Give your card content a fixed height for the tidiest stack.
Usage
"use client"
import { CardStack } from "@/components/dusk/card-stack/card-stack"
const people = [
{ name: "Ava", bio: "Designer" },
{ name: "Marcus", bio: "Founder" },
{ name: "Priya", bio: "Engineer" },
]
export function Deck() {
return (
<CardStack
items={people}
getKey={(p) => p.name}
cardClassName="p-6"
onSwipe={(direction, person) => console.log(direction, person.name)}
renderItem={(p) => (
<div className="h-40">
<p className="text-lg font-semibold">{p.name}</p>
<p className="text-sm text-muted-foreground">{p.bio}</p>
</div>
)}
/>
)
}Examples
Finite stack with callbacks
With loop={false} the stack ends and shows empty. onSwipe receives the direction and item, and labels renames the buttons. Change the stack's key to start over.
Would you use this?
Dark mode scheduling
Switch themes at sunset automatically.
Card 1 of 5
Your votes
- Swipe, click or use ← →
"use client";
import * as React from "react";
import { Check, RotateCcw, X } from "lucide-react";
import { CardStack, type SwipeDirection } from "@/components/dusk/card-stack/card-stack";
const features = [
{ title: "Dark mode scheduling", detail: "Switch themes at sunset automatically." },
{ title: "Offline drafts", detail: "Keep writing on the train; sync when you're back." },
{ title: "Shared workspaces", detail: "Invite your team and edit together in real time." },
{ title: "Command palette", detail: "Every action, two keystrokes away." },
{ title: "Weekly digest", detail: "A Monday email with what changed last week." },
];
type Decision = { title: string; direction: SwipeDirection };
export default function CardStackDecisions() {
const [decisions, setDecisions] = React.useState<Decision[]>([]);
const [round, setRound] = React.useState(0);
return (
<div className="grid w-full gap-8 rounded-xl border border-white/10 bg-background p-6 sm:grid-cols-[1fr_200px] sm:p-10">
<CardStack
// A new key starts a fresh stack.
key={round}
items={features}
loop={false}
visible={4}
offset={10}
label="Feature voting"
labels={{ left: "Skip", right: "Want it" }}
className="mx-auto"
cardClassName="p-5"
onSwipe={(direction, item) => setDecisions((d) => [...d, { title: item.title, direction }])}
empty={
<span className="flex flex-col items-center gap-3">
Thanks for voting.
<button
type="button"
onClick={() => {
setDecisions([]);
setRound((r) => r + 1);
}}
className="inline-flex items-center gap-1.5 rounded-md border border-white/10 px-3 py-1.5 text-xs text-white transition-colors hover:border-white/20 hover:bg-white/[0.04]"
>
<RotateCcw className="size-3.5" /> Vote again
</button>
</span>
}
renderItem={(f) => (
<div className="flex h-36 flex-col justify-between">
<p className="text-sm text-white/50">Would you use this?</p>
<div>
<p className="text-lg font-semibold text-white">{f.title}</p>
<p className="mt-1 text-sm text-white/60">{f.detail}</p>
</div>
</div>
)}
/>
<div>
<p className="text-sm font-medium text-white">Your votes</p>
<ul className="mt-3 space-y-2 text-sm">
{decisions.length === 0 && <li className="text-white/55">Swipe, click or use ← →</li>}
{decisions.map((d) => (
<li key={d.title} className="flex items-center gap-2 text-white/70">
{d.direction === "right" ? (
<Check aria-label="Want it" className="size-4 text-foreground" />
) : (
<X aria-label="Skip" className="size-4 text-white/55" />
)}
{d.title}
</li>
))}
</ul>
</div>
</div>
);
}Deep stack without buttons
visible, offset and scaleStep shape the pile. With controls={false} it is swiped by drag or with the arrow keys once focused.
Graphite
#3f3f46
Card 1 of 5
"use client";
import { CardStack } from "@/components/dusk/card-stack/card-stack";
const themes = [
{ name: "Graphite", color: "#3f3f46" },
{ name: "Sand", color: "#d6d3d1" },
{ name: "Moss", color: "#4d5b3a" },
{ name: "Clay", color: "#9a6b52" },
{ name: "Slate", color: "#475569" },
];
export default function CardStackGradients() {
return (
<div className="flex w-full justify-center rounded-xl border border-white/10 bg-background px-6 py-10">
<CardStack
items={themes}
getKey={(t) => t.name}
visible={5}
offset={8}
scaleStep={0.04}
controls={false}
label="Themes"
className="max-w-[260px]"
cardClassName="overflow-hidden border-white/15"
renderItem={(t) => (
<div className="flex aspect-[3/4] flex-col justify-end">
<div className="flex-1" style={{ background: t.color }} />
<div className="p-4">
<p className="text-sm font-medium text-white">{t.name}</p>
<p className="font-mono text-xs text-white/50">{t.color}</p>
</div>
</div>
)}
/>
</div>
);
}API Reference
Any other div prop is passed to the root. A drag past threshold or a fast flick counts as a swipe; anything less springs the card back.
| Prop | Type | Default | Description |
|---|---|---|---|
| items | T[] | — | The data for each card. |
| renderItem | (item: T, index: number) => ReactNode | — | Renders one card's content. |
| getKey | (item: T, index: number) => Key | — | Stable key for an item. Defaults to its index. |
| loop | boolean | true | Start over after the last card. |
| visible | number | 3 | How many cards are visible in the pile. |
| offset | number | 14 | How far each card behind peeks out, in px. |
| scaleStep | number | 0.05 | How much smaller each card behind is. |
| threshold | number | 100 | Drag distance in px that counts as a swipe. |
| draggable | boolean | true | Let people drag the top card away. |
| controls | boolean | true | Show the swipe left / right buttons and the counter. |
| onSwipe | (direction: "left" | "right", item: T, index: number) => void | — | Called when a card leaves. |
| onEnd | () => void | — | Called after the last card when loop is off. |
| empty | ReactNode | "No more cards" | Shown when a finite stack is done. |
| labels | { left?: string; right?: string } | — | Accessible labels for the buttons. |
| label | string | "Card stack" | Accessible name of the stack. |
| cardClassName | string | — | Classes for every card. |
Accessibility
- The stack is a focusable, labelled region: ArrowLeft and ArrowRight swipe the top card.
- The buttons have accessible labels and use aria-disabled when the stack is done, so focus is never lost.
- Only the top card is exposed; cards behind it are
inertand hidden from assistive tech. - A polite live region announces "Card 2 of 5" after every swipe.
- With prefers-reduced-motion cards no longer fly or rotate: they simply crossfade.