I'm currently focused on defining the "complex" aspect of the desired drag-and-drop interface. Simple DnD is easy; the challenge lies in identifying the features that elevate it to "complex." Are we talking about nested droppable areas, dynamic content, or custom visual feedback? Pinpointing these elements is key.
Mapping Out Components
Now, I'm sketching out the component hierarchy. Thinking about how the data model will relate to the visual components. The App component will manage overall state. Then, I'll need KanbanBoard, Column, and Card components, each handling their respective DnD interactions. Considering the data flow, the KanbanBoard will likely pass data to the Column components.
Structuring the Data Flow
The structure is becoming clearer. The plan is to have a centralized state held within the App component that contains all the data for the columns and tasks, which will get passed down to children. Thinking about how the data will be managed in each drag and drop action is critical. The aim is to update the state correctly after each item movement.
Detailing the Implementation
Now I'm delving into the specifics of the implementation. I've sketched out the TaskCard component, making it both draggable and a drop target for reordering, to be consistent with standard React DnD sortable list examples. I'm focusing on the data structure and move logic, especially the moveCard function, which needs to handle both within-column reordering and cross-column moves. This will be the trickiest part, I suspect.
Designing the Kanban Board
I'm now solidifying the architecture. The Kanban board will be the central metaphor, with columns and tasks. I've broken down "complex" into features like column-to-column movements and reordering, which drives the design. It's becoming clearer what components are needed, and how they interact to support a good user experience.
Implementing with useRef
Now, I'm focusing on the refactoring the TaskCard component to implement reordering logic using useRef. This will give more precise control over calculating the hover index. The goal is to move beyond simple "append to end" on column moves, and towards true sortable list behavior. This approach is key to making this interface robust.
Implementing The Move Logic
I'm now grappling with the moveCard function, which needs to be the central mover of the data to facilitate both reordering and column transfers. Ensuring data integrity during these actions will be crucial. I'm leaning toward an immutable approach to updating the state to prevent unexpected bugs. I need to make sure the state updates are accurate after each move action.
This request requires building a Kanban-style board (like Trello). This is considered a "complex" scenario because it involves:
Vertical Sorting: Reordering items within a single list.
Horizontal Movement: Moving items seamlessly between different lists (columns).
Ref Handling: Managing DOM measurements to prevent UI flickering during hover events.
The Stack
React
react-dnd: The core logic library.
react-dnd-html5-backend: The implementation of the HTML5 Drag and Drop API.
immutability-helper: (Optional but highly recommended) Makes updating nested state arrays much easier. I will use standard JS spread syntax here to minimize dependencies, but keep in mind specific libraries exist for this.
Step 1: Install Dependencies
bash
npm install react-dnd react-dnd-html5-backend
Step 2: Define Constants (ItemTypes.js)
We need a unique identifier for the type of item we are dragging.
This is the most complex component. It acts as both a Drag Source (allows it to be picked up) and a Drop Target (allows it to detect when another card is hovering over it to trigger a swap).
jsx
import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { ItemTypes } from './ItemTypes';
const style = {
border: '1px solid dashed gray',
padding: '0.5rem 1rem',
marginBottom: '.5rem',
backgroundColor: 'white',
cursor: 'move',
borderRadius: '4px',
boxShadow: '0 1px 3px rgba(0,0,0,0.12)',
};
export const Card = ({ id, text, index, moveCard, status }) => {
const ref = useRef(null);
// 1. Configure the Drop Target (for reordering)
const [, drop] = useDrop({
accept: ItemTypes.CARD,
hover(item, monitor) {
if (!ref.current) return;
const dragIndex = item.index;
const hoverIndex = index;
const sourceStatus = item.status;
const targetStatus = status;
// Don't replace items with themselves
if (dragIndex === hoverIndex && sourceStatus === targetStatus) return;
// Determine rectangle on screen
const hoverBoundingRect = ref.current?.getBoundingClientRect();
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging Downwards within same list
if (sourceStatus === targetStatus && dragIndex < hoverIndex && hoverClientY < hoverMiddleY) return;
// Dragging Upwards within same list
if (sourceStatus === targetStatus && dragIndex > hoverIndex && hoverClientY > hoverMiddleY) return;
// Perform the action
moveCard(dragIndex, hoverIndex, sourceStatus, targetStatus);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
item.index = hoverIndex;
item.status = targetStatus;
},
});
// 2. Configure the Drag Source
const [{ isDragging }, drag] = useDrag({
type: ItemTypes.CARD,
item: { id, index, status }, // Data passed to the 'hover' function above
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
// Initializes drag and drop on the element
drag(drop(ref));
return (
<div ref={ref} style={{ ...style, opacity: isDragging ? 0.5 : 1 }}>
{text}
</div>
);
};
Step 4: The Column Component (Column.jsx)
The column needs to be a drop target as well. Why? If a column is empty, or if you drag an item to the very bottom of a list, the individual Cards won't catch the hover event. The Column catches it.
This holds the state and the Complex logic for moving items in the array.
jsx
import React, { useState, useCallback } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Column } from './Column';
// Mock Data
const initialData = [
{ id: 1, content: 'Fix Login Bug', status: 'todo' },
{ id: 2, content: 'Add Dark Mode', status: 'todo' },
{ id: 3, content: 'Write Documentation', status: 'in-progress' },
{ id: 4, content: 'Update API Keys', status: 'done' },
];
const KanbanBoard = () => {
const [tasks, setTasks] = useState(initialData);
// This function handles both reordering in the same column
// AND moving between different columns
const moveCard = useCallback((dragIndex, hoverIndex, sourceStatus, targetStatus) => {
setTasks((prevTasks) => {
// 1. Create a deep copy (or at least a shallow copy of the array)
let newTasks = [...prevTasks];
// 2. Find the item being dragged
// Note: In a real app with huge data, don't filter every time.
// This is simplified for clarity.
const dragItem = newTasks.find(
(t, i) => t.status === sourceStatus && getColumnIndex(newTasks, sourceStatus, t.id) === dragIndex
);
if(!dragItem) return prevTasks;
// 3. Remove the item from the source
// We filter it out temporarily
const tasksWithoutDragged = newTasks.filter(t => t.id !== dragItem.id);
// 4. Calculate the new insertion point
// We act as if we are inserting into the target column
const targetColumnTasks = tasksWithoutDragged.filter(t => t.status === targetStatus);
// 5. Insert into the new position
// We reconstruct the array locally for the specific column
targetColumnTasks.splice(hoverIndex, 0, { ...dragItem, status: targetStatus });
// 6. Merge everything back together
const otherTasks = tasksWithoutDragged.filter(t => t.status !== targetStatus);
return [...otherTasks, ...targetColumnTasks];
});
}, []);
// Helper to find the actual index within a specific status subset
const getColumnIndex = (allTasks, status, id) => {
const columnTasks = allTasks.filter(t => t.status === status);
return columnTasks.findIndex(t => t.id === id);
}
return (
<DndProvider backend={HTML5Backend}>
<div style={{ display: 'flex', justifyContent: 'center', height: '100vh', padding: '50px' }}>
{['todo', 'in-progress', 'done'].map(status => (
<Column
key={status}
status={status}
tasks={tasks.filter(t => t.status === status)}
moveCard={moveCard}
/>
))}
</div>
</DndProvider>
);
};
export default KanbanBoard;
How it works
The Provider: <DndProvider backend={HTML5Backend}> wraps the app. This sets up the HTML5 Drag and Drop capabilities (event listeners on the window).
Monitor & Collection: React DnD uses a "monitor" to track the global state of the drag. The collect function in useDrag and useDrop lets you extract that state (e.g., isDragging, isOver) to update your UI styles.
The Sorting Logic (The hardest part):
Inside Card.js, the hover function fires repeatedly as you drag a card 1 pixel over another card.
We use ref.current.getBoundingClientRect() to determine the physical midpoint of the card underneath the mouse.
We only trigger a moveCard action when the mouse crosses that midpoint. This prevents the UI from flickering violently (swapping back and forth instantly).
The moveCard function in App.js updates the React state. Because state updates cause re-renders, the card physically moves in the DOM, creating the illusion of drag-and-drop.
Key Considerations for complexity
Performance: In the moveCard function, I used filtering and splicing. For a production app with 1000+ items, you would want to normalize your state (e.g., Object of IDs) or use immutability-helper to perform O(1) updates instead of array scans.
Touch Devices: react-dnd-html5-backend does not support touch screens (phones/tablets). You would need to use react-dnd-touch-backend and potentially switch backends based on the device type.