Create an advanced drag-and-drop kanban board in React with real-time collaboration.
- User
Create an advanced drag-and-drop kanban board in React with real-time collaboration.
Assistant
Conceptualizing the Kanban Board
I've been contemplating the core requirements of this React Kanban board. I've broken down the project, starting with a focus on real-time collaboration. I'm now zeroing in on React and its capabilities. I'm focusing on the user's advanced needs as a baseline for my approach.
Analyzing Technology Choices
I'm now deep-diving into the libraries. I've switched gears to
@dnd-kit/coreand@dnd-kit/sortableto sidestep those StrictMode gotchas. I think they offer a better blend of ease of use and modern flexibility, crucial for a good user experience. Furthermore, I've got my mind on Firebase or Supabase for the backend, leaning toward Firebase for simpler integration in the example.Prioritizing Project Structure
I've been mentally charting the project's course. I'm focusing on the component hierarchy, starting with a main Kanban board component. Thinking of having separate components for the columns and individual cards, all to ensure a clean and maintainable codebase. Thinking about how the data flow will work, and how to best manage the state for drag-and-drop actions and real-time updates.
Planning Real-time Simulation
I've been working on a method for demonstrating real-time updates without needing a full-fledged backend right away. I've chosen the
BroadcastChannelAPI to simulate real-time updates across browser tabs. This will enable users to see changes reflected in different tabs without any server setup, which makes the example much more accessible. I'll need to create a custom hook for state management to handle this.Defining Data and Components
I'm now establishing my data models and core components. I'm focusing on the
TaskandColumntypes in Typescript. I'm also mapping out the basic structure of theKanbanBoardcomponent, which will house the columns and coordinate drag-and-drop events. I will be prioritizing clean data structures to maintain state easily, and support a robust foundation for drag-and-drop operations and efficient real-time updates.Structuring the Real-time Logic
I'm now focusing on creating a state management solution with Zustand and a custom middleware. This will facilitate real-time updates across tabs using
BroadcastChannel. My next step is designing how this middleware will interact with the drag-and-drop actions, making sure state changes are broadcast effectively. Then I'll show how to switch to Firebase or Supabase.Planning Detailed Implementation
I'm now mapping out the components and the real-time update engine in greater detail. I've switched gears to using Zustand, combined with a custom middleware to manage state and sync changes using
BroadcastChannel. This allows for a great user experience on a single page, and I can swap it out later. I will also incorporate UI/UX improvements, with animation frames and styling with Tailwind CSS.This is a complex request that requires a robust frontend architecture. To satisfy the "Advanced" and "Real-time" requirements, we will use:
- React 18 + TypeScript: For type safety and performance.
- @hello-pangea/dnd: The maintained fork of
react-beautiful-dnd. It is the standard for list-based drag-and-drop. - Zustand: For state management.
- BroadcastChannel API: To simulate serverless real-time collaboration between browser tabs. I will explain how to swap this for Firebase/Socket.io at the end.
- Tailwind CSS: For styling.
Prerequisites
Create a project and install dependencies:
npm create vite@latest kanban-board -- --template react-ts cd kanban-board npm install @hello-pangea/dnd zustand uuid lucide-react npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p(Ensure you add the Tailwind directives to your
index.css).The Implementation
Here is the full, copy-pasteable solution broken down into modular components.
1. The Types (
src/types.ts)export type TaskStatus = 'todo' | 'in-progress' | 'done'; export interface Task { id: string; content: string; status: TaskStatus; } export interface Columns { [key: string]: { name: string; items: Task[]; }; }2. The Store with Real-Time Sync (
src/store.ts)This is the brain. We use Zustand to manage state. I have added a
BroadcastChannellistener here. If you open this app in two different tabs, moving a card in one will move it in the other instantly.import { create } from 'zustand'; import { v4 as uuidv4 } from 'uuid'; import { Columns, Task, TaskStatus } from './types'; interface BoardState { columns: Columns; moveTask: (source: any, destination: any) => void; addTask: (columnId: string) => void; deleteTask: (columnId: string, taskId: string) => void; setColumns: (columns: Columns) => void; // Used for sync } // Initial Data const initialColumns: Columns = { todo: { name: 'To Do', items: [{ id: '1', content: 'Research Competitors', status: 'todo' }] }, 'in-progress': { name: 'In Progress', items: [{ id: '2', content: 'Design System', status: 'in-progress' }] }, done: { name: 'Done', items: [] }, }; // Real-time Channel const channel = new BroadcastChannel('kanban_channel'); export const useBoardStore = create<BoardState>((set) => { // Listen for updates from other tabs channel.onmessage = (event) => { set({ columns: event.data }); }; return { columns: initialColumns, setColumns: (columns) => set({ columns }), addTask: (columnId) => set((state) => { const newTask: Task = { id: uuidv4(), content: 'New Task', status: columnId as TaskStatus }; const newColumns = { ...state.columns, [columnId]: { ...state.columns[columnId], items: [newTask, ...state.columns[columnId].items], }, }; channel.postMessage(newColumns); // Sync return { columns: newColumns }; }), deleteTask: (columnId, taskId) => set((state) => { const newColumns = { ...state.columns, [columnId]: { ...state.columns[columnId], items: state.columns[columnId].items.filter((t) => t.id !== taskId), }, }; channel.postMessage(newColumns); // Sync return { columns: newColumns }; }), moveTask: (source, destination) => set((state) => { if (!destination) return state; const sourceCol = state.columns[source.droppableId]; const destCol = state.columns[destination.droppableId]; const sourceItems = [...sourceCol.items]; const destItems = source.droppableId === destination.droppableId ? sourceItems : [...destCol.items]; const [removed] = sourceItems.splice(source.index, 1); if (source.droppableId === destination.droppableId) { sourceItems.splice(destination.index, 0, removed); const newCol = { ...sourceCol, items: sourceItems }; const newColumns = { ...state.columns, [source.droppableId]: newCol }; channel.postMessage(newColumns); // Sync return { columns: newColumns }; } else { removed.status = destination.droppableId as TaskStatus; destItems.splice(destination.index, 0, removed); const newColumns = { ...state.columns, [source.droppableId]: { ...sourceCol, items: sourceItems }, [destination.droppableId]: { ...destCol, items: destItems }, }; channel.postMessage(newColumns); // Sync return { columns: newColumns }; } }), }; });3. The Task Card Component (
src/components/TaskCard.tsx)import React from 'react'; import { Draggable } from '@hello-pangea/dnd'; import { X } from 'lucide-react'; interface Props { item: any; index: number; columnId: string; onDelete: (colId: string, id: string) => void; } export const TaskCard: React.FC<Props> = ({ item, index, columnId, onDelete }) => { return ( <Draggable draggableId={item.id} index={index}> {(provided, snapshot) => ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} style={{ ...provided.draggableProps.style, // Transform allows for smoother hardware acceleration }} className={` relative p-4 mb-3 rounded-lg shadow-sm text-sm font-medium transition-colors duration-200 select-none border ${snapshot.isDragging ? 'bg-indigo-50 border-indigo-300 shadow-xl rotate-2 scale-105 z-50' : 'bg-white border-gray-200 hover:border-indigo-300'} `} > <div className="flex justify-between items-center group"> <span>{item.content}</span> <button onClick={() => onDelete(columnId, item.id)} className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 transition-opacity" > <X size={16} /> </button> </div> </div> )} </Draggable> ); };4. The Main Board Logic (
src/components/KanbanBoard.tsx)import React from 'react'; import { DragDropContext, Droppable } from '@hello-pangea/dnd'; import { Plus } from 'lucide-react'; import { useBoardStore } from '../store'; import { TaskCard } from './TaskCard'; export const KanbanBoard: React.FC = () => { const { columns, moveTask, addTask, deleteTask } = useBoardStore(); return ( <div className="flex h-full w-full gap-6 overflow-x-auto p-8 items-start"> <DragDropContext onDragEnd={(result) => moveTask(result.source, result.destination)}> {Object.entries(columns).map(([columnId, column]) => ( <div key={columnId} className="flex flex-col w-80 shrink-0"> {/* Column Header */} <div className="flex items-center justify-between mb-4 p-1"> <h2 className="font-bold text-gray-700 flex items-center gap-2"> <span className={`w-3 h-3 rounded-full ${ columnId === 'todo' ? 'bg-orange-400' : columnId === 'in-progress' ? 'bg-blue-400' : 'bg-green-400' }`} /> {column.name} <span className="text-gray-400 text-xs font-normal bg-gray-100 px-2 py-0.5 rounded-full"> {column.items.length} </span> </h2> <button onClick={() => addTask(columnId)} className="p-1 hover:bg-gray-200 rounded transition-colors" > <Plus size={18} className="text-gray-500" /> </button> </div> {/* Droppable Area */} <Droppable droppableId={columnId}> {(provided, snapshot) => ( <div {...provided.droppableProps} ref={provided.innerRef} className={` flex-1 p-2 rounded-xl transition-colors min-h-[150px] ${snapshot.isDraggingOver ? 'bg-gray-100/50' : 'bg-gray-50'} `} > {column.items.map((item, index) => ( <TaskCard key={item.id} item={item} index={index} columnId={columnId} onDelete={deleteTask} /> ))} {provided.placeholder} </div> )} </Droppable> </div> ))} </DragDropContext> </div> ); };5. Application Entry (
src/App.tsx)import { KanbanBoard } from './components/KanbanBoard'; function App() { return ( <div className="min-h-screen bg-white text-slate-900"> <header className="border-b border-gray-200 px-8 py-4 bg-white"> <h1 className="text-xl font-bold bg-gradient-to-r from-indigo-600 to-violet-600 bg-clip-text text-transparent"> Collaboration Board </h1> <p className="text-xs text-gray-500 mt-1"> Open this URL in a second tab to see real-time synchronization. </p> </header> <main className="h-[calc(100vh-85px)] bg-dots"> <KanbanBoard /> </main> </div> ); } export default App;How to verify Real-Time Collaboration
- Run
npm run dev. - Open
http://localhost:5173in Chrome. - Open the same URL in Firefox or a new Chrome Window.
- Drag a card from "To Do" to "Done".
- Observed Result: The card moves smoothly in the window you dragged it in. In the second window, the card simply snaps to the new position instantly.
Moving to Production Backend (Firebase)
The
BroadcastChannelonly works for tabs on the same computer. To make this work across the world (different computers), you need a database.Here is how to modify
src/store.tsto use Firebase Firestore:- Replace
BroadcastChannellogic withonSnapshot:
// In src/store.ts import { doc, onSnapshot, setDoc } from "firebase/firestore"; import { db } from "./firebase-config"; // Your firebase init file // Inside your store creator... useBoardStore = create((set, get) => { // 1. Listen to DB useEffect(() => { // Subscribe to a document 'boards/demo-board' const unsub = onSnapshot(doc(db, "boards", "demo-board"), (doc) => { if (doc.exists()) { // Update local state to match server set({ columns: doc.data().columns }); } }); return () => unsub(); }, []); return { // ... existing logic ... // 2. Modify Actions to write to DB moveTask: (source, dest) => { // Perform optimistic update (update UI immediately) set(state => { ...logic to update local state... }); // Send new state to DB const newState = get().columns; setDoc(doc(db, "boards", "demo-board"), { columns: newState }); } } });Key "Advanced" Features Explained
- Optimistic UI: In the code above, we update the
Zustandstore before the network/channel sync happens. This ensures the drag feels 60fps smooth to the user performing the action, even if the network is slow. - Column-Specific Coloring: Logic is included to style columns dynamically based on ID.
- Drag Transformation: When dragging, the card is slightly rotated (
rotate-2) and scaled (scale-105) using Tailwind classes to give it a tactile, physical feel. - Droppable Placeholder: The line
{provided.placeholder}ensures the column grows to make space for the item you are hovering over before you drop it.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.