Building a Kanban Deal Pipeline in React with Drag and Drop

Shaz3e blog cover for react kanban board: Building a Kanban Deal Pipeline in React with Drag and Drop.

A deal pipeline is the screen people open first in most CRMs: columns for stages, cards for deals, and you drag a card when a deal moves forward. This tutorial builds a React kanban board for that job with dnd-kit. It covers dragging between columns, saving the move with an optimistic update that rolls back on failure, and making the whole thing work with a keyboard and a screen reader.

If you’re designing the rest of the CRM too, start with my guide to CRM architecture and data modeling. This post sticks to the front end.

Versions tested: React 19.3.1, @dnd-kit/core 6.3.1, @dnd-kit/sortable 10.0.0, Vite 8.3.7, TypeScript 7.0.2 and Vitest 5.1.0. All 12 tests in the demo pass.

Why dnd-kit for a React kanban board

Native HTML drag and drop doesn’t work with a keyboard and behaves differently on touch screens. You’d end up writing your own sensors anyway. dnd-kit gives you pointer, touch and keyboard sensors, a sortable preset for lists, and screen reader announcements out of the box. It doesn’t render any markup for you, so the board stays your own components.

One thing to know before you install it. The dnd-kit docs now file @dnd-kit/core and @dnd-kit/sortable under “Legacy”, because the authors are working on a new @dnd-kit/react package. That package was at 0.5.3 when I wrote this, so I’ve used the stable 6.x line here. The ideas below carry over either way.

npm i @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities

Model the pipeline as plain data

Keep the board as a record of stage ids to arrays of deals. The order of the array is the order on screen. That makes every move a small, pure function you can test without rendering anything.

export type StageId = 'new' | 'qualified' | 'proposal' | 'won';

export interface Deal {
  id: string;
  title: string;
  value: number;
}

export type Board = Record<StageId, Deal[]>;

export const STAGES: { id: StageId; label: string }[] = [
  { id: 'new', label: 'New' },
  { id: 'qualified', label: 'Qualified' },
  { id: 'proposal', label: 'Proposal' },
  { id: 'won', label: 'Won' },
];

The move function removes the deal from its stage and splices it into the target at an index. It returns a new board and never touches the old one, which matters later: the old board is what we roll back to.

import type { Board, StageId } from './types';

export function findStage(board: Board, id: string): StageId | undefined {
  if (id in board) return id as StageId;
  return (Object.keys(board) as StageId[]).find((stage) =>
    board[stage].some((deal) => deal.id === id),
  );
}

/**
 * Move a deal to a stage at a given index. Returns a new board and never
 * mutates the old one, so the previous board can be kept for rollback.
 */
export function moveDeal(
  board: Board,
  dealId: string,
  toStage: StageId,
  toIndex: number,
): Board {
  const fromStage = findStage(board, dealId);
  if (!fromStage) return board;

  const deal = board[fromStage].find((d) => d.id === dealId)!;
  const next: Board = { ...board, [fromStage]: board[fromStage].filter((d) => d.id !== dealId) };
  const target = [...next[toStage]];
  const index = Math.max(0, Math.min(toIndex, target.length));
  target.splice(index, 0, deal);
  next[toStage] = target;
  return next;
}

export function positionOf(board: Board, dealId: string) {
  const stage = findStage(board, dealId);
  if (!stage) return undefined;
  return { stage, index: board[stage].findIndex((d) => d.id === dealId) };
}

Columns and draggable deal cards

Each deal card uses useSortable. Spreading attributes onto the card gives it role="button", a tabindex and an aria-describedby that points to the keyboard instructions, so you get focus handling without extra work.

import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { Deal } from './types';

export function DealCard({ deal }: { deal: Deal }) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
    useSortable({ id: deal.id });

  return (
    <li
      ref={setNodeRef}
      style={{
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
      }}
      className="deal-card"
      {...attributes}
      {...listeners}
    >
      <strong>{deal.title}</strong>
      <span>${deal.value.toLocaleString('en-US')}</span>
    </li>
  );
}

Each column is a droppable area with its own SortableContext. The droppable part matters for empty stages: without it, there’s no card to drop onto and the deal can’t land in an empty column. The header also shows the count and the total value, which is the number sales teams actually look at.

import { useDroppable } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import type { Deal, StageId } from './types';
import { DealCard } from './DealCard';

export function StageColumn({ id, label, deals }: { id: StageId; label: string; deals: Deal[] }) {
  const { setNodeRef } = useDroppable({ id });
  const total = deals.reduce((sum, d) => sum + d.value, 0);

  return (
    <section className="stage" aria-labelledby={`stage-${id}`}>
      <h2 id={`stage-${id}`}>
        {label} <small>{deals.length} · ${total.toLocaleString('en-US')}</small>
      </h2>
      <SortableContext items={deals.map((d) => d.id)} strategy={verticalListSortingStrategy}>
        <ul ref={setNodeRef} className="stage-list">
          {deals.map((deal) => (
            <DealCard key={deal.id} deal={deal} />
          ))}
        </ul>
      </SortableContext>
    </section>
  );
}

Optimistic updates with rollback

When someone drops a card, it should stay where they dropped it right away. Waiting for the server before moving the card feels broken, even on a fast connection. So the board moves first and saves second. If the save fails, the deal goes back and the user sees a short message.

I keep that logic in a hook so it can be tested on its own:

import { useRef, useState } from 'react';
import type { Board, StageId } from './types';
import { moveDeal, positionOf } from './moveDeal';

export type PersistMove = (dealId: string, stage: StageId, index: number) => Promise<void>;

export function useOptimisticBoard(initial: Board, persist: PersistMove) {
  const [board, setBoard] = useState(initial);
  const [error, setError] = useState<string | null>(null);
  const snapshot = useRef<Board | null>(null);
  const latest = useRef(board);
  latest.current = board;

  function startDrag() {
    snapshot.current = latest.current;
    setError(null);
  }

  function preview(dealId: string, stage: StageId, index: number) {
    setBoard((b) => moveDeal(b, dealId, stage, index));
  }

  function cancel() {
    if (snapshot.current) setBoard(snapshot.current);
    snapshot.current = null;
  }

  async function commit(dealId: string, stage: StageId, index: number) {
    const before = snapshot.current ?? latest.current;
    snapshot.current = null;
    const after = moveDeal(latest.current, dealId, stage, index);
    setBoard(after);

    const was = positionOf(before, dealId);
    if (was && was.stage === stage && was.index === index) return;

    try {
      await persist(dealId, stage, index);
    } catch {
      // Only roll back if nothing else changed the board in the meantime.
      setBoard((current) => (current === after ? before : current));
      setError('Could not save that move. The deal is back where it was.');
    }
  }

  return { board, error, startDrag, preview, cancel, commit };
}

A few details are worth pointing out:

  • startDrag takes a snapshot of the board before any preview moves, so a cancelled drag can restore it exactly.
  • commit skips the request when the deal ends up in the same stage and position it started from. A click that turns into a tiny drag shouldn’t hit your API.
  • The rollback only applies if the board is still the one we set. If another change landed while the request was in flight, we don’t throw it away.
  • The error uses role="alert" in the board, so screen readers hear it too.

If your pipeline data already lives in TanStack Query, you can do the same thing with onMutate and onError on a mutation. I walk through that pattern in my post on server state and TanStack Query. The hook here keeps the example free of extra libraries.

The save itself is a single PATCH request. Send the stage and the new position, and let the server reorder the other cards in that stage inside a transaction:

import type { PersistMove } from './useOptimisticBoard';

export const persistMove: PersistMove = async (dealId, stage, index) => {
  const res = await fetch(`/api/deals/${dealId}/move`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
    body: JSON.stringify({ stage, position: index }),
  });
  if (!res.ok) throw new Error(`Move failed with ${res.status}`);
};

Wiring the board together

The board component sets up the sensors, handles the drag events and passes the results to the hook. Moving across columns happens in onDragOver, so the card visibly jumps into the new column while you’re still dragging. Sorting inside one column is left to dnd-kit’s transforms until the drop.

import {
  DndContext,
  KeyboardSensor,
  PointerSensor,
  closestCorners,
  useSensor,
  useSensors,
  type Announcements,
  type DragEndEvent,
  type DragOverEvent,
} from '@dnd-kit/core';
import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
import { STAGES, type Board } from './types';
import { findStage } from './moveDeal';
import { useOptimisticBoard, type PersistMove } from './useOptimisticBoard';
import { StageColumn } from './StageColumn';

function target(board: Board, overId: string) {
  const stage = findStage(board, overId)!;
  const index = overId === stage ? board[stage].length : board[stage].findIndex((d) => d.id === overId);
  return { stage, index };
}

export function PipelineBoard({ initial, persist }: { initial: Board; persist: PersistMove }) {
  const { board, error, startDrag, preview, cancel, commit } = useOptimisticBoard(initial, persist);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
  );

  const title = (id: string | number) => {
    const stage = findStage(board, String(id));
    return board[stage!]?.find((d) => d.id === id)?.title ?? String(id);
  };
  const stageLabel = (id: string | number) =>
    STAGES.find((s) => s.id === findStage(board, String(id)))?.label ?? '';

  const announcements: Announcements = {
    onDragStart: ({ active }) => `Picked up ${title(active.id)}.`,
    onDragOver: ({ active, over }) =>
      over ? `${title(active.id)} is over ${stageLabel(over.id)}.` : undefined,
    onDragEnd: ({ active, over }) =>
      over ? `${title(active.id)} dropped in ${stageLabel(over.id)}.` : `${title(active.id)} dropped.`,
    onDragCancel: ({ active }) => `Move cancelled. ${title(active.id)} went back.`,
  };

  function onDragOver({ active, over }: DragOverEvent) {
    if (!over) return;
    const from = findStage(board, String(active.id));
    const to = target(board, String(over.id));
    // Only reorder across columns here; same-column sorting is handled by dnd-kit's transforms.
    if (from && from !== to.stage) preview(String(active.id), to.stage, to.index);
  }

  function onDragEnd({ active, over }: DragEndEvent) {
    if (!over) return cancel();
    const to = target(board, String(over.id));
    void commit(String(active.id), to.stage, to.index);
  }

  return (
    <>
      {error && <p role="alert">{error}</p>}
      <DndContext
        sensors={sensors}
        collisionDetection={closestCorners}
        accessibility={{
          announcements,
          screenReaderInstructions: {
            draggable:
              'To pick up a deal, press space or enter. Use the arrow keys to move it between stages. Press space or enter again to drop it, or escape to cancel.',
          },
        }}
        onDragStart={startDrag}
        onDragOver={onDragOver}
        onDragEnd={onDragEnd}
        onDragCancel={cancel}
      >
        <div className="board">
          {STAGES.map((s) => (
            <StageColumn key={s.id} id={s.id} label={s.label} deals={board[s.id]} />
          ))}
        </div>
      </DndContext>
    </>
  );
}

The pointer sensor has an activation distance of 5 pixels. Without it, every click on a card starts a drag, which gets in the way as soon as cards have links or buttons on them. closestCorners works better than the default collision detection for tall columns stacked side by side.

Keyboard accessibility for drag and drop

This is the part most kanban tutorials skip, and it’s the part that decides whether some of your users can use the board at all. With the setup above, a keyboard user can:

  1. Tab to a card.
  2. Press space or enter to pick it up.
  3. Use the arrow keys to move it to another stage or position.
  4. Press space or enter to drop it, or escape to cancel.

sortableKeyboardCoordinates is what makes the arrow keys jump between sortable items instead of moving the card a few pixels at a time. The keyboard sensor docs explain the options if you need custom key bindings.

The default screen reader messages say things like “Draggable item d3 was moved over droppable area qualified”. Ids mean nothing to a person, so the board passes its own announcements that use the deal title and the stage label. I also rewrote the instructions to say “stages” instead of “items”. The dnd-kit accessibility guide lists every message you can override.

Two more checks I’d do on any real pipeline:

  • Give cards a visible focus style. Browsers draw one by default, but a lot of CSS resets remove it.
  • Offer a second way to change the stage, like a select menu on the deal page. Drag and drop with a keyboard works, but it’s slow for someone moving ten deals.

Testing the pipeline

Pointer and keyboard dragging depend on real layout, which jsdom doesn’t have, so I test the logic rather than the gesture. The pure move function gets unit tests, the hook gets tests for success, failure, cancel and the no-op case, and the board gets a render test that checks the cards are focusable and point to the keyboard instructions.

it('rolls back and shows an error when saving fails', async () => {
  const persist = vi.fn().mockRejectedValue(new Error('500'));
  const { result } = renderHook(() => useOptimisticBoard(initial, persist));
  act(() => result.current.startDrag());
  await act(() => result.current.commit('a', 'won', 0));
  expect(result.current.board.new.map((d) => d.id)).toEqual(['a']);
  expect(result.current.board.won).toHaveLength(0);
  expect(result.current.error).toMatch(/back where it was/);
});

For the drag gesture itself, run a Playwright test against the built app in a real browser. Keep that suite small. The logic it depends on is already covered.

Where to take it next

  • Add a DragOverlay so the dragged card floats above columns with overflow hidden.
  • Virtualize long columns once a stage holds a few hundred deals.
  • Store positions as gaps (1000, 2000, 3000) or fractional keys, so a move only updates one row on the server.
  • Split the board into a feature folder as it grows. My guide to structuring large React apps shows the layout I use.

Before you build the UI, get the stages right. The board can only be as useful as the stages on it, and EloSync’s guide on choosing sales pipeline stages is a good place to settle those first.

FAQ

Is dnd-kit still a good choice for a React kanban board?

Yes. The 6.x packages are stable and widely used, and they work with React 19. Keep an eye on @dnd-kit/react, which is the authors’ next version, and plan a move once it reaches a stable release.

Does this work on touch screens?

The pointer sensor handles touch through pointer events. On mobile, consider a short press delay in the activation constraint so a scroll doesn’t start a drag.

Can I use this in a Next.js app?

Yes. The board uses state and browser events, so mark the file that renders it with 'use client'. Fetch the pipeline in a server component and pass it in as initial.

What if two people move the same deal at once?

The last write wins unless the server checks. Send a version number with the move and return a 409 when it’s stale. The hook already rolls back on any error, so the user sees the deal snap back and can refresh.


I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *