Overview

Grab a card and it lifts off the board: it follows the pointer freely on both axes, leans into the direction you drag, and a dashed slot opens where it will land, with neighbours sliding out of the way. Release and the card flies into that slot before the real card takes its place, with a brief outline to mark where it landed. Esc (or a lost pointer) sends it back to where it started. The board auto-scrolls when you hold a card near its edges, column counts roll as cards come and go, and the arrow keys on a card's handle move it without a pointer.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/kanban-board.json

Install dependencies:

$ pnpm add motion lucide-react

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Copy the component code into your project:

components/ui/kanban-board.tsx
tsx
"use client";
import React, {  useCallback,  useEffect,  useId,  useRef,  useState,} from "react";import { createPortal } from "react-dom";import {  AnimatePresence,  LayoutGroup,  animate,  motion,  useMotionValue,  useReducedMotion,  useSpring,  useTransform,  useVelocity,  type MotionValue,} from "motion/react";import { GripVertical } from "lucide-react";import { cn } from "@/lib/utils";
export type KanbanCard = {  id: string;  title: string;  meta?: string;  /** Small label shown above the title, e.g. a team or priority. */  tag?: string;};
export type KanbanColumn = {  id: string;  title: string;  cards: KanbanCard[];  /** Colour of the dot next to the column title. */  accent?: string;};
export type KanbanMove = {  cardId: string;  fromColumn: string;  toColumn: string;  index: number;};
export type KanbanBoardProps = {  /**   * Columns. Without `onChange` this is the initial state and the board   * manages moves itself. With `onChange` the board is controlled by this prop.   */  columns: KanbanColumn[];  onChange?: (columns: KanbanColumn[]) => void;  /** Fires once per completed move (pointer drop or keyboard). */  onCardMove?: (move: KanbanMove) => void;  className?: string;};
type MoveDirection = "up" | "down" | "left" | "right";
type DragState = {  card: KanbanCard;  fromCol: string;  fromIndex: number;  overCol: string;  overIndex: number;  width: number;  height: number;  grabX: number;  grabY: number;  phase: "drag" | "drop";};
type Pending = {  card: KanbanCard;  colId: string;  index: number;  startX: number;  startY: number;  rect: DOMRect;};
const LAYOUT_SPRING = { type: "spring" as const, bounce: 0, duration: 0.3 };const DROP_SPRING = { type: "spring" as const, bounce: 0.12, duration: 0.34 };const DRAG_THRESHOLD = 4;const EDGE = 48;const DEFAULT_ACCENTS = ["#a1a1aa", "#f59e0b", "#3b82f6", "#10b981", "#a855f7"];
function cloneColumns(cols: KanbanColumn[]): KanbanColumn[] {  return cols.map((c) => ({ ...c, cards: [...c.cards] }));}
function findCard(cols: KanbanColumn[], cardId: string) {  for (let i = 0; i < cols.length; i++) {    const j = cols[i].cards.findIndex((c) => c.id === cardId);    if (j >= 0) return { colIndex: i, cardIndex: j };  }  return null;}
function moveCard(  cols: KanbanColumn[],  cardId: string,  toCol: string,  toIndex: number,): KanbanColumn[] | null {  const loc = findCard(cols, cardId);  if (!loc) return null;  const next = cloneColumns(cols);  const [card] = next[loc.colIndex].cards.splice(loc.cardIndex, 1);  const target = next.find((c) => c.id === toCol);  if (!target || !card) return null;  target.cards.splice(Math.min(toIndex, target.cards.length), 0, card);  return next;}
/* -------------------------------------------------------------------------- */
function CardFace({  card,  lifted = false,  gripProps,}: {  card: KanbanCard;  lifted?: boolean;  gripProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {    ref?: React.Ref<HTMLButtonElement>;  };}) {  return (    <div      className={cn(        "group/card relative flex items-start gap-1 rounded-[12px] bg-(--color-paper) py-2.5 pr-3 pl-1.5",        "shadow-[inset_0_0_0_1px_var(--color-rule),0_1px_2px_rgba(0,0,0,0.04)]",        lifted &&          "shadow-[inset_0_0_0_1px_var(--color-rule),0_2px_4px_rgba(0,0,0,0.06),0_18px_40px_-12px_rgba(0,0,0,0.28)] dark:shadow-[inset_0_0_0_1px_var(--color-rule),0_18px_40px_-12px_rgba(0,0,0,0.7)]",      )}    >      <button        type="button"        tabIndex={gripProps ? undefined : -1}        aria-hidden={gripProps ? undefined : true}        data-kanban-grip=""        {...gripProps}        className={cn(          "flex size-7 shrink-0 touch-none items-center justify-center rounded-[8px] outline-none",          "text-(--color-neutral) opacity-60 transition-[opacity,background-color,color,transform] duration-150",          "group-hover/card:opacity-100 focus-visible:opacity-100 active:scale-[0.94]",          "focus-visible:ring-2 focus-visible:ring-(--color-focus)",          "[@media(hover:hover)]:hover:bg-(--color-paper-2) [@media(hover:hover)]:hover:text-(--color-ink)",          "[@media(hover:none)]:opacity-100",          lifted && "text-(--color-ink) opacity-100",        )}      >        <GripVertical className="size-3.5" strokeWidth={1.75} aria-hidden />      </button>      <div className="min-w-0 flex-1 pt-[3px]">        {card.tag ? (          <div className="mb-1 inline-flex h-[18px] items-center rounded-full bg-(--color-paper-2) px-1.5 text-[10.5px] leading-none font-medium text-(--color-ink-2)">            {card.tag}          </div>        ) : null}        <div className="text-[13.5px] leading-snug font-medium text-pretty text-(--color-ink)">          {card.title}        </div>        {card.meta ? (          <div className="mt-1 text-[12px] leading-tight text-(--color-neutral)">            {card.meta}          </div>        ) : null}      </div>    </div>  );}
function DragOverlay({  drag,  x,  y,  reduce,}: {  drag: DragState;  x: MotionValue<number>;  y: MotionValue<number>;  reduce: boolean;}) {  // Lean into the direction of travel, like a card held by its corner.  const vx = useVelocity(x);  const tilt = useTransform(vx, [-1800, 0, 1800], [-7, 0, 7], { clamp: true });  const rotate = useSpring(tilt, { stiffness: 420, damping: 32 });
  return createPortal(    <motion.div      aria-hidden      style={{        position: "fixed",        left: 0,        top: 0,        zIndex: 90,        width: drag.width,        x,        y,        rotate: reduce ? 0 : rotate,        transformOrigin: `${drag.grabX}px ${drag.grabY}px`,        pointerEvents: "none",        cursor: "grabbing",      }}    >      <motion.div        initial={{ scale: 1 }}        animate={{ scale: reduce || drag.phase === "drop" ? 1 : 1.035 }}        transition={{ type: "spring", bounce: 0, duration: 0.25 }}      >        <CardFace card={drag.card} lifted={drag.phase === "drag"} />      </motion.div>    </motion.div>,    document.body,  );}
function CountBadge({ value, active }: { value: number; active: boolean }) {  return (    <span      className={cn(        "relative inline-flex h-5 min-w-5 items-center justify-center overflow-hidden rounded-full px-1.5",        "text-[11px] leading-none font-medium tabular-nums transition-colors duration-200",        active          ? "bg-(--color-ink) text-(--color-paper)"          : "bg-(--color-paper) text-(--color-neutral) shadow-[inset_0_0_0_1px_var(--color-rule)]",      )}    >      <AnimatePresence initial={false} mode="popLayout">        <motion.span          key={value}          initial={{ y: 8, opacity: 0, filter: "blur(2px)" }}          animate={{ y: 0, opacity: 1, filter: "blur(0px)" }}          exit={{ y: -8, opacity: 0, filter: "blur(2px)" }}          transition={{ type: "spring", bounce: 0, duration: 0.3 }}        >          {value}        </motion.span>      </AnimatePresence>    </span>  );}
/* -------------------------------------------------------------------------- */
export function KanbanBoard({  columns: columnsProp,  onChange,  onCardMove,  className,}: KanbanBoardProps) {  const reduce = !!useReducedMotion();  const boardId = useId();  const hintId = `${boardId}-hint`;  // Uncontrolled: `columnsProp` only seeds state, like a defaultValue.  const [internal, setInternal] = useState(columnsProp);  const columns = onChange ? columnsProp : internal;
  const [drag, setDragState] = useState<DragState | null>(null);  const [landed, setLanded] = useState<{ id: string; token: number } | null>(null);  const [announcement, setAnnouncement] = useState("");
  const dragRef = useRef<DragState | null>(null);  const pending = useRef<Pending | null>(null);  const pointer = useRef({ x: 0, y: 0 });  const columnsRef = useRef(columns);  const pendingFocus = useRef<string | null>(null);  const scrollerRef = useRef<HTMLDivElement>(null);  const gripRefs = useRef(new Map<string, HTMLButtonElement>());  const x = useMotionValue(0);  const y = useMotionValue(0);
  useEffect(() => {    columnsRef.current = columns;  }, [columns]);
  const setDrag = useCallback((next: DragState | null) => {    dragRef.current = next;    setDragState(next);  }, []);
  const commit = useCallback(    (next: KanbanColumn[], move: KanbanMove) => {      if (onChange) onChange(next);      else setInternal(next);      onCardMove?.(move);    },    [onChange, onCardMove],  );
  // Keyboard moves remount or reorder the row; give focus back to its grip.  useEffect(() => {    const id = pendingFocus.current;    if (!id) return;    pendingFocus.current = null;    gripRefs.current.get(id)?.focus();  });
  /* ------------------------------ hit testing ----------------------------- */
  const hitTest = useCallback(() => {    const d = dragRef.current;    if (!d || d.phase !== "drag") return;    const { x: px, y: py } = pointer.current;    const colEl = document      .elementsFromPoint(px, py)      .find((el) => (el as HTMLElement).dataset?.kanbanCol) as HTMLElement | undefined;    // Off the board the slot stays where it was, so a sloppy release still lands.    if (!colEl || !colEl.closest(`[data-kanban-board="${boardId}"]`)) return;    const colId = colEl.dataset.kanbanCol!;    const list = colEl.querySelector<HTMLElement>("[data-kanban-list]");    if (!list) return;
    // Compare the floating card's centre with each card's layout midpoint.    // offsetTop ignores in-flight layout transforms, so the slot never jitters.    const centre = py - d.grabY + d.height / 2 - list.getBoundingClientRect().top;    const cards = list.querySelectorAll<HTMLElement>("[data-kanban-card]");    let index = cards.length;    for (let i = 0; i < cards.length; i++) {      const el = cards[i];      if (centre < el.offsetTop + el.offsetHeight / 2) {        index = i;        break;      }    }    if (colId !== d.overCol || index !== d.overIndex) {      setDrag({ ...d, overCol: colId, overIndex: index });    }  }, [boardId, setDrag]);
  /* ------------------------------ drag lifecycle -------------------------- */
  const startDrag = useCallback(    (p: Pending) => {      const { rect } = p;      x.jump(rect.left);      y.jump(rect.top);      document.documentElement.style.cursor = "grabbing";      document.documentElement.style.userSelect = "none";      setDrag({        card: p.card,        fromCol: p.colId,        fromIndex: p.index,        overCol: p.colId,        overIndex: p.index,        width: rect.width,        height: rect.height,        grabX: p.startX - rect.left,        grabY: p.startY - rect.top,        phase: "drag",      });    },    [setDrag, x, y],  );
  const finish = useCallback(    (accept: boolean) => {      const d = dragRef.current;      if (!d || d.phase !== "drag") return;      document.documentElement.style.cursor = "";      document.documentElement.style.userSelect = "";      const target: DragState = accept        ? { ...d, phase: "drop" }        : { ...d, overCol: d.fromCol, overIndex: d.fromIndex, phase: "drop" };      setDrag(target);
      // Wait one frame for the placeholder to take its final slot, then fly      // the floating card into it before swapping in the real card.      requestAnimationFrame(() => {        const ph = document.querySelector<HTMLElement>(          `[data-kanban-board="${boardId}"] [data-kanban-placeholder]`,        );        const list = ph?.offsetParent as HTMLElement | null;        const done = () => {          const moved =            target.overCol !== target.fromCol || target.overIndex !== target.fromIndex;          if (accept && moved) {            const next = moveCard(              columnsRef.current,              target.card.id,              target.overCol,              target.overIndex,            );            if (next) {              commit(next, {                cardId: target.card.id,                fromColumn: target.fromCol,                toColumn: target.overCol,                index: target.overIndex,              });              setLanded({ id: target.card.id, token: Date.now() });              const col = next.find((c) => c.id === target.overCol);              setAnnouncement(                `${target.card.title} dropped in ${col?.title}, position ${target.overIndex + 1} of ${col?.cards.length}.`,              );            }          }          setDrag(null);        };        if (!ph || !list || reduce) return done();        const box = list.getBoundingClientRect();        Promise.all([          animate(x, box.left + ph.offsetLeft, DROP_SPRING),          animate(y, box.top + ph.offsetTop, DROP_SPRING),        ]).then(done);      });    },    [boardId, commit, reduce, setDrag, x, y],  );
  useEffect(() => {    const onMove = (e: PointerEvent) => {      pointer.current = { x: e.clientX, y: e.clientY };      const p = pending.current;      if (p && !dragRef.current) {        if (Math.hypot(e.clientX - p.startX, e.clientY - p.startY) < DRAG_THRESHOLD) return;        pending.current = null;        startDrag(p);      }      const d = dragRef.current;      if (!d || d.phase !== "drag") return;      x.set(e.clientX - d.grabX);      y.set(e.clientY - d.grabY);      hitTest();    };    const onUp = () => {      pending.current = null;      finish(true);    };    const onCancel = () => {      pending.current = null;      finish(false);    };    const onKey = (e: KeyboardEvent) => {      if (e.key === "Escape" && dragRef.current?.phase === "drag") {        e.preventDefault();        finish(false);      }    };    window.addEventListener("pointermove", onMove);    window.addEventListener("pointerup", onUp);    window.addEventListener("pointercancel", onCancel);    window.addEventListener("keydown", onKey);    return () => {      window.removeEventListener("pointermove", onMove);      window.removeEventListener("pointerup", onUp);      window.removeEventListener("pointercancel", onCancel);      window.removeEventListener("keydown", onKey);    };  }, [finish, hitTest, startDrag, x, y]);
  // Edge auto-scroll while a card is held near the board's sides.  const dragging = drag?.phase === "drag";  useEffect(() => {    if (!dragging) return;    let raf = 0;    const tick = () => {      const el = scrollerRef.current;      if (el && el.scrollWidth > el.clientWidth) {        const r = el.getBoundingClientRect();        const px = pointer.current.x;        const dx =          px < r.left + EDGE            ? -((r.left + EDGE - px) / EDGE) * 14            : px > r.right - EDGE              ? ((px - (r.right - EDGE)) / EDGE) * 14              : 0;        if (dx) {          el.scrollLeft += dx;          hitTest();        }      }      raf = requestAnimationFrame(tick);    };    raf = requestAnimationFrame(tick);    return () => cancelAnimationFrame(raf);  }, [dragging, hitTest]);
  useEffect(    () => () => {      document.documentElement.style.cursor = "";      document.documentElement.style.userSelect = "";    },    [],  );
  const onCardPointerDown = (    e: React.PointerEvent<HTMLDivElement>,    card: KanbanCard,    colId: string,    index: number,  ) => {    if (!e.isPrimary || e.button !== 0 || dragRef.current) return;    const target = e.target as Element;    // Touch scrolls the page from the card body; the grip is the touch handle.    if (e.pointerType === "touch" && !target.closest("[data-kanban-grip]")) return;    if (e.pointerType === "mouse") e.preventDefault();    pending.current = {      card,      colId,      index,      startX: e.clientX,      startY: e.clientY,      rect: e.currentTarget.getBoundingClientRect(),    };  };
  /* -------------------------------- keyboard ------------------------------ */
  const moveCardByKey = (cardId: string, direction: MoveDirection) => {    const cols = columnsRef.current;    const loc = findCard(cols, cardId);    if (!loc) return;    const from = cols[loc.colIndex];    const card = from.cards[loc.cardIndex];    let toCol = from;    let toIndex = loc.cardIndex;
    if (direction === "up" || direction === "down") {      toIndex += direction === "up" ? -1 : 1;      if (toIndex < 0 || toIndex >= from.cards.length) return;    } else {      const neighbour = cols[loc.colIndex + (direction === "left" ? -1 : 1)];      if (!neighbour) return;      toCol = neighbour;      toIndex = Math.min(loc.cardIndex, neighbour.cards.length);    }
    const next = moveCard(cols, cardId, toCol.id, toIndex);    if (!next) return;    pendingFocus.current = cardId;    commit(next, { cardId, fromColumn: from.id, toColumn: toCol.id, index: toIndex });    const size = next.find((c) => c.id === toCol.id)?.cards.length ?? 0;    setAnnouncement(      toCol === from        ? `${card.title} moved to position ${toIndex + 1} of ${size} in ${from.title}.`        : `${card.title} moved to ${toCol.title}, position ${toIndex + 1} of ${size}.`,    );  };
  const keyToDirection: Record<string, MoveDirection> = {    ArrowUp: "up",    ArrowDown: "down",    ArrowLeft: "left",    ArrowRight: "right",  };
  /* --------------------------------- render ------------------------------- */
  return (    <LayoutGroup id={boardId}>      <div id={hintId} className="sr-only">        Drag a card by its handle, or focus the handle and use the arrow keys:        Up and Down reorder within a column, Left and Right move the card to the        neighbouring column.      </div>      <div        ref={scrollerRef}        data-kanban-board={boardId}        className={cn(          "flex items-stretch gap-3 overflow-x-auto pb-2 [scrollbar-width:thin]",          className,        )}      >        {columns.map((col, colIndex) => {          const headingId = `${boardId}-col-${col.id}`;          const isOver = !!drag && drag.overCol === col.id;          const isForeignTarget = isOver && drag.fromCol !== col.id;          const visible = drag            ? col.cards.filter((c) => c.id !== drag.card.id)            : col.cards;          const count = visible.length + (isOver ? 1 : 0);          const accent = col.accent ?? DEFAULT_ACCENTS[colIndex % DEFAULT_ACCENTS.length];
          const rows: React.ReactNode[] = visible.map((card, i) => {            const flash = landed?.id === card.id;            return (              <motion.div                key={card.id}                layout={reduce ? false : "position"}                transition={LAYOUT_SPRING}                role="listitem"                data-kanban-card=""                onPointerDown={(e) => onCardPointerDown(e, card, col.id, i)}                className="relative cursor-grab rounded-[12px] transition-transform duration-150 [@media(hover:hover)]:hover:-translate-y-px"              >                <CardFace                  card={card}                  gripProps={{                    ref: (el: HTMLButtonElement | null) => {                      if (el) gripRefs.current.set(card.id, el);                      else gripRefs.current.delete(card.id);                    },                    "aria-label": `Move ${card.title}`,                    "aria-describedby": hintId,                    onKeyDown: (e) => {                      const dir = keyToDirection[e.key];                      if (!dir) return;                      e.preventDefault();                      moveCardByKey(card.id, dir);                    },                  }}                />                {flash && !reduce ? (                  <motion.span                    key={landed.token}                    aria-hidden                    initial={{ opacity: 1 }}                    animate={{ opacity: 0 }}                    transition={{ duration: 0.9, ease: "easeOut" }}                    className="pointer-events-none absolute inset-0 rounded-[12px] shadow-[inset_0_0_0_1.5px_var(--color-ink)]"                  />                ) : null}              </motion.div>            );          });
          if (isOver) {            rows.splice(              Math.min(drag.overIndex, rows.length),              0,              <motion.div                key="placeholder"                layout={reduce ? false : "position"}                transition={LAYOUT_SPRING}                data-kanban-placeholder=""                aria-hidden                initial={false}                className={cn(                  "rounded-[12px] border border-dashed",                  isForeignTarget                    ? "border-(--color-ink)/30 bg-(--color-ink)/[0.04]"                    : "border-(--color-rule) bg-(--color-paper)/50",                )}                style={{ height: drag.height }}              />,            );          }
          return (            <div              key={col.id}              role="group"              aria-labelledby={headingId}              data-kanban-col={col.id}              className={cn(                "flex w-64 shrink-0 flex-col rounded-[18px] p-2",                "bg-(--color-paper-2) shadow-[inset_0_0_0_1px_transparent]",                "transition-[box-shadow,background-color] duration-200 ease-out",                isForeignTarget &&                  "bg-[color-mix(in_oklab,var(--color-ink)_5%,var(--color-paper-2))] shadow-[inset_0_0_0_1px_var(--color-rule)]",              )}            >              <div className="mb-2 flex items-center gap-2 px-1.5 pt-1">                <span                  aria-hidden                  className="size-2 shrink-0 rounded-full"                  style={{                    background: accent,                    boxShadow: `0 0 0 3px color-mix(in oklab, ${accent} 22%, transparent)`,                  }}                />                <div                  id={headingId}                  className="min-w-0 flex-1 truncate text-[13px] font-semibold text-(--color-ink)"                >                  {col.title}                </div>                <CountBadge value={count} active={isForeignTarget} />              </div>              <div                role="list"                aria-labelledby={headingId}                data-kanban-list=""                className="relative flex min-h-[4.75rem] flex-1 flex-col gap-2"              >                {rows}                {rows.length === 0 ? (                  <div className="flex h-[4.75rem] items-center justify-center rounded-[12px] border border-dashed border-(--color-rule) text-[12px] text-(--color-neutral)">                    No cards                  </div>                ) : null}              </div>            </div>          );        })}      </div>      {drag ? <DragOverlay drag={drag} x={x} y={y} reduce={reduce} /> : null}      <div role="status" aria-live="polite" className="sr-only">        {announcement}      </div>    </LayoutGroup>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { KanbanBoard, type KanbanColumn } from "@/components/ui/kanban-board";
const [columns, setColumns] = useState<KanbanColumn[]>([  { id: "todo", title: "Ready", accent: "#a1a1aa", cards: [{ id: "1", tag: "Billing", title: "Wire refund webhook", meta: "P1" }] },  { id: "doing", title: "In progress", accent: "#f59e0b", cards: [] },]);
<KanbanBoard  columns={columns}  onChange={setColumns}  onCardMove={({ cardId, toColumn, index }) => save(cardId, toColumn, index)}/>

Props

PropTypeRequiredDefaultDescription
columnsKanbanColumn[]Yes—Columns with id, title, optional accent colour and cards ({ id, title, meta?, tag? }). Without onChange this is only the initial state.
onChange(columns: KanbanColumn[]) => voidNo—Makes the board controlled. Fires once per completed move with the new columns.
onCardMove(move: { cardId, fromColumn, toColumn, index }) => voidNo—Fires once per completed move, for pointer drops and keyboard moves. Handy for persisting a single change.
classNamestringNo—Class names on the scrolling board row.

Best Practices

  1. With a mouse, grab a card anywhere; on touch, use the handle so the page can still scroll from the card body.
  2. Keyboard: focus a card's handle and use the arrow keys. Up and Down reorder within a column; Left and Right move it to the neighbouring column. Each move is announced.
  3. Persist from onCardMove when your API stores single moves, or from onChange when it stores the whole board.
  4. Keep titles short and put status in meta and tag; cards stay easy to scan while they move.
  5. For a single list, use Reorder List instead.