Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 132 ยท Projects

Project: Kanban Board

Build a Kanban board in React step by step: columns and cards, a reducer for add, move and delete, keyboard-friendly buttons, and drag and drop with the native browser API.

A Kanban board is a set of columns, usually "To do", "In progress" and "Done", with cards that travel from left to right as work gets done. It is a wonderful practice project because it looks simple and hides a real design question: how do you store data that lives in several places at once? The same card belongs to exactly one column, columns show many cards, and every action (add, move, delete) touches the same shared list.

In this project you will build the board in four stages. First you will render a static board from data. Then you will move all changes into a reducer. Then you will add a form and an empty state. Finally you will add drag and drop with the browser's built-in API, while keeping buttons so the board works from a keyboard too. If any of the building blocks feel unfamiliar, revisit lists and keys, useReducer and choosing state structure first.

Step 0: decide what the state looks like

Before writing any JSX, decide where the truth lives. There are two popular shapes for a board.

Nested: each column owns an array of cards, like { todo: [card, card], doing: [card] }. Moving a card means removing it from one array and inserting it in another, and finding a card by id means searching every column.

Flat: one array of cards, and each card says which column it is in, like { id: 1, title: 'Buy milk', column: 'todo' }. A column is then just a derived view: cards.filter((card) => card.column === 'todo').

We will use the flat shape. A card exists exactly once, so it can never be in two columns by mistake, moving a card is one field change, and the order of cards inside a column is simply their order in the array. This is the "avoid duplicated state, derive the rest" rule from choosing state structure in action.

JavaScript
const initialState = {
  nextId: 4,
  cards: [
    { id: 1, title: 'Sketch the layout', column: 'done' },
    { id: 2, title: 'Write the reducer', column: 'doing' },
    { id: 3, title: 'Add drag and drop', column: 'todo' },
  ],
};

Notice nextId is part of the state. Generating ids inside a reducer with Date.now() or a module counter would make the reducer impure, and React may call a reducer twice in development. A counter that lives in the state is deterministic.

Step 1: render a static board

Start with no interactivity at all. Three components are enough: Board maps over the column definitions, Column receives its cards, and Card shows one title. The column list is a constant outside the components because it never changes.

Stage 1: a static board

Look at the two key props. Columns are keyed by their stable id, and cards by theirs. Never key by array index here: when a card moves to another column its index changes, and React would reuse the wrong DOM node and any state inside it. The heading shows cards.length, a count we did not store anywhere; it is computed during render from the filtered list.

Step 2: move every change into a reducer

Now we need three actions: added, moved and deleted. Writing them as a reducer gives us one place that describes every legal change to the board.

JavaScript
function boardReducer(state, action) {
  switch (action.type) {
    case 'added':
      return {
        nextId: state.nextId + 1,
        cards: [
          ...state.cards,
          { id: state.nextId, title: action.title, column: action.column },
        ],
      };
    case 'moved': {
      const card = state.cards.find((c) => c.id === action.id);
      if (!card || card.column === action.column) {
        return state;
      }
      const others = state.cards.filter((c) => c.id !== action.id);
      return { ...state, cards: [...others, { ...card, column: action.column }] };
    }
    case 'deleted':
      return { ...state, cards: state.cards.filter((c) => c.id !== action.id) };
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

Two details deserve attention. First, moved removes the card and appends a changed copy at the end of the array, so a card dropped into a column lands at the bottom of it. Second, when the card is already in the target column, or does not exist, the reducer returns the same state object. React compares by reference, so it skips the re-render entirely. Returning the old state is how a reducer says "nothing happened".

A reducer is just a function, so you can test it without any UI. This is one of the best reasons to use one; see testing hooks and logic for more. Run it here and read the log.

Testing the reducer as a plain function

The log shows that the reducer never changes start, that moving into the same column hands back the identical object, and that a typo in an action name fails loudly instead of silently doing nothing.

Step 3: a working board with a form

Now connect the reducer to the screen. The board owns the state with useReducer and passes down plain callbacks. Each column gets an add form with its own small piece of local state (the text being typed); that text does not belong in the reducer because nobody else needs it.

Moving works with two buttons per card, "Move left" and "Move right". They are real <button> elements, so they are focusable, work with Enter and Space, and are announced properly by screen readers. The first card in the first column has no left neighbour, so that button is disabled. Using column positions to find the neighbour keeps the logic in one expression.

Stage 3: add, move and delete with buttons

Add a card to "To do", move it right twice, then delete it. Everything runs through dispatch, and the components contain no list-editing code. Passing dispatch down is fine here because it has a stable identity. If the tree were deeper, you would put it in context instead of threading it through every level.

The text of each add form lives in AddCardForm and nowhere else. When you press "Add" in one column, the other two forms do not re-render their input values, because their state is separate. Keep state as low as it can go; lift it only when two components need to agree on it (lifting state up).

Step 4: drag and drop

Buttons are accessible but slow. Mouse users expect to drag. The browser already has a drag and drop API, so you need no library: an element with draggable="true" fires dragstart; a drop target cancels the default of dragover (otherwise the browser refuses drops) and reads the data in drop. React exposes these as onDragStart, onDragOver and onDrop.

The plan:

  1. In Card, onDragStart stores the card id in event.dataTransfer.
  2. In Column, onDragOver calls event.preventDefault() to say "dropping here is allowed", and onDrop reads the id and dispatches moved.
  3. Highlight the column that is currently under the pointer. That highlight is UI state, so it lives in Column as isOver.
JSX
// inside Card
<li
  draggable="true"
  onDragStart={(event) => {
    event.dataTransfer.setData('text/plain', String(card.id));
    event.dataTransfer.effectAllowed = 'move';
  }}
>

// inside Column
<section
  onDragOver={(event) => { event.preventDefault(); setIsOver(true); }}
  onDragLeave={() => setIsOver(false)}
  onDrop={(event) => {
    event.preventDefault();
    setIsOver(false);
    dispatch({ type: 'moved', id: Number(event.dataTransfer.getData('text/plain')), column: column.id });
  }}
>

dataTransfer only holds strings, which is why the id is converted with String and back with Number. The reducer already ignores a drop into the card's own column, so you need no extra check. Here is the complete board with the buttons kept next to the drag support. Drag a card by its text to another column.

Stage 4: the finished board with drag and drop

Native drag and drop is not available on most touch screens, and it is hard to use with a keyboard or a screen reader. That is why the buttons stay. For polished sorting inside a column, touch support and keyboard dragging, teams usually add a dedicated library; drag and drop and gestures shows how pointer events work from scratch and what a library takes off your hands.

Where to take it next

  • Ordering inside a column. Add a beforeId to the moved action and insert the card at that position instead of appending it.
  • Editing titles. Add an edited action; double-click a card to switch it into an input.
  • Persistence. Our sandbox blocks localStorage, but in a real app you would load the initial state lazily and save on change; see useEffect and external stores.
  • Undo. Because every change goes through the reducer, you can keep a history array of past states.
  • Performance. Each card re-renders when any card moves. With hundreds of cards, wrap Card in memo (memo) and keep dispatch as the only function prop, which is already stable.

What you practised

The structure of this project is worth remembering more than the CSS. State is flat and normalized, so each card exists once. The columns are derived with filter during render. All changes go through a pure reducer, which you tested on its own. Small pieces of purely local state (the text in a form, whether a column is highlighted) stay in the component that needs them. Interactions have an accessible path (buttons) in addition to the fancy one (dragging).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the board store cards in one flat array with a column field instead of one array per column?

    With a flat list a card cannot appear in two columns by mistake, and a move is a one-field change. Columns are derived with filter during render. Nested state would also work, but moving a card would mean editing two arrays.
  2. 2. The reducer returns the same state object when a card is moved to its current column. What does React do?

    React compares the old and new state with Object.is. The identical reference means nothing changed, so there is nothing to re-render. Returning the old state is the correct way for a reducer to ignore an action.
  3. 3. Why is the next card id stored inside the reducer state instead of being created with Date.now() in the reducer?

    A reducer has to give the same result for the same inputs. A counter held in the state is deterministic, while the clock is not.
  4. 4. What must the onDragOver handler of a drop target do for onDrop to fire?

    By default the browser treats an element as not accepting drops. Cancelling the dragover default marks it as a valid target, so the drop event fires.
  5. 5. Why do the cards keep their Move buttons even though dragging works?

    Pointer-only interactions exclude many people. Real buttons are focusable, announced by assistive technology and work on touch screens.

Summary

  • Choose a state shape first: one flat array of cards with a column field, and derive each column with filter during render.
  • Put every change (added, moved, deleted) in a pure reducer; keep ids deterministic by storing a counter in the state, and return the same object for no-op actions.
  • Test the reducer as a plain function before wiring it to the UI.
  • Keep local UI state (form text, hover highlight) in the component that owns it.
  • Native drag and drop needs draggable, onDragStart with dataTransfer, preventDefault in onDragOver, and a handler in onDrop; always keep a keyboard-friendly alternative.

Next: Project: Quiz App