The user wants a complex drag-and-drop interface using React DnD in React.
This request is a bit ambiguous regarding "complex". Does it mean:
- Multiple drag sources and drop targets?
- Nested drag-and-drop (dragging containers within containers)?
- Moving items between lists (Kanban style)?
- Custom drag previews and handles?
To provide a robust answer, I should aim for a scenario that covers the most common "complex" use cases: A Kanban Board (moving cards between columns) or a Nested List.
A Kanban board is generally the best example to demonstrate the core features of React DnD:
- Drag Sources: Cards.
- Drop Targets: Columns (to move cards) and potentially the board itself (if moving columns, but let's stick to cards to keep it digestible yet complex enough).
- State Management: Updating the state based on drop actions.
- Customization: Using a custom drag layer (optional but adds "complexity"/polish).
Plan:
- Prerequisites: Mention necessary packages (
react-dnd, react-dnd-html5-backend).
- Setup: Create the main component context (
DndProvider).
- Types: Define constants for item types (good practice).
- The Card (Draggable Item):
- Use
useDrag.
- Handle opacity changes while dragging.
- Pass necessary ID info.
- The Column (Drop Target):
- Use
useDrop.
- Accept the card type.
- Logic to add the card to this specific list.
- The Container/State Management:
- Hold the data structure (e.g., an object where keys are column IDs and values are arrays of cards).
- Implement the logic to remove a card from source and add to destination.
- Handle reordering (optional, but makes it truly "complex"). Self-correction: Reordering within a list using native HTML5 backend without a library like
dnd-kit is tricky with just hover index calculations. I will implement a simpler version: Moving between lists. If I try to do reordering, the code becomes very verbose for a single prompt response.
- Decision: Let's stick to Moving items between lists (Kanban style). It's complex enough to show off React DnD but not so math-heavy that it obscures the React DnD API usage.
Refining the "Complex" aspect:
To make it stand out, I'll add:
- Styling: Basic CSS to make it look like a board.
- State Logic: Immer or standard spread operators to ensure immutability.
- Custom Drag Layer: (Maybe too much code? I'll keep it simple but mention it).
Step-by-Step Code Structure:
- Imports & Setup:
DndProvider, HTML5Backend.
- Data Structure:
tasks state.
TaskCard Component: Uses useDrag.
Column Component: Uses useDrop.
KanbanBoard Component: Renders columns and manages state.
Drafting the Code (Mental or Scratchpad):
- State:
{ todo: [{id: 1, text: 'a'}], done: [...] }.
- Move Logic:
moveCard(cardId, sourceCol, destCol).
- useDrag:
type: 'CARD', item: { id, columnId }, collect: (monitor) => ({ isDragging: ... }).
- useDrop:
accept: 'CARD', drop: (item) => moveCard(item.id, item.columnId, props.columnId).
Wait, there's a nuance.
If I move a card, I need to know where it came from to remove it.
When defining the drag item in useDrag, I should include the currentColumnId.
Let's write the code.
- File 1: Types (constants)
- File 2: Card (Draggable)
- File 3: Column (Droppable)
- File 4: Main App (State + Provider)
Dependencies:
npm install react-dnd react-dnd-html5-backend
Constraint Check:
The user asked for "Complex". A simple 2-list transfer is standard. To make it complex, I should try to handle the visual "ghosting" (opacity) and perhaps ensure the ref forwarding is done correctly, as that is a common pitfall.
Implementation details:
- Use
forwardRef? Not strictly necessary if wrapping a div, but good practice.
useDrag returns drag.
useDrop returns drop.
- Join refs using
react-dnd's internal utilities or manual assignment ref={node => drag(drop(node))} if an item is both draggable and droppable (nested lists). Here, Columns are droppable, Cards are draggable. They are separate, so refs don't need merging on the same node.
Let's refine the state logic for the "Move":
const handleDrop = (id, sourceColumn, targetColumn) => {
if (sourceColumn === targetColumn) return; // Optional optimization
// Find item in source
// Remove from source
// Add to target
}
Adding styling:
I will use inline styles or a simple CSS object to keep it copy-pasteable without needing a CSS file setup, but clean enough to visualize.
Final Polish:
Ensure the explanation covers why things are done (Hooks, Providers, Backends).
Let's build the response.
- Introduction: Explain React DnD concepts (Provider, Backends, Hooks).
- Prerequisites: Install command.
- The Code: A single file (or clearly separated sections) for a Kanban Board.
- Step 1: Item Types.
- Step 2: The Draggable Card.
- Step 3: The Drop Zone (Column).
- Step 4: The Container (State).
- Key takeaways: Explain
useDrag, useDrop, and the monitor.
This looks solid. I will generate the code now.
This is a complete implementation of a Kanban Board using react-dnd. It represents a "complex" interface because it handles:
- Multiple Drop Targets: Moving items between different lists.
- State Management: Complex immutable state updates to move items without mutation.
- Dynamic Styling: Visual feedback when dragging over a zone.
- Modular Architecture: Separation of concerns between Cards, Zones, and the Board context.
Prerequisites
First, ensure you install the core library and the HTML5 backend:
npm install react-dnd react-dnd-html5-backend
The Implementation
We will create a single-file example (for easy copying) that consists of:
- ItemTypes: Constants for drag types.
- Card: The draggable item.
- Column: The drop target zone.
- KanbanBoard: The container managing the state.
KanbanBoard.jsx
import React, { useState, useCallback, useRef } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
// --- 1. Constants ---
const ItemTypes = {
CARD: 'card',
};
// --- 2. Styles (Inline for simplicity) ---
const styles = {
container: {
display: 'flex',
justifyContent: 'center',
gap: '20px',
padding: '20px',
fontFamily: 'Arial, sans-serif',
minHeight: '100vh',
background: '#f0f2f5',
},
column: {
width: '300px',
minHeight: '400px',
backgroundColor: '#ebecf0',
borderRadius: '8px',
padding: '10px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
transition: 'background-color 0.2s ease',
},
columnActive: {
backgroundColor: '#e0e6ed',
border: '2px dashed #999',
},
card: {
padding: '15px',
margin: '8px 0',
backgroundColor: 'white',
borderRadius: '4px',
boxShadow: '0 1px 3px rgba(0,0,0,0.12)',
cursor: 'grab',
userSelect: 'none',
transition: 'opacity 0.2s, transform 0.2s',
},
draggingCard: {
opacity: 0.5,
transform: 'rotate(3deg)',
},
};
// --- 3. Draggable Card Component ---
const Card = ({ id, text, columnId, moveCard }) => {
const ref = useRef(null);
const [{ isDragging }, drag] = useDrag({
type: ItemTypes.CARD,
item: { id, text, sourceColumnId: columnId },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
// We attach the drag ref to the component DOM element
drag(ref);
return (
<div
ref={ref}
style={{
...styles.card,
...(isDragging ? styles.draggingCard : {}),
}}
>
{text}
</div>
);
};
// --- 4. Droppable Column Component ---
const Column = ({ id, title, cards, moveCard }) => {
const ref = useRef(null);
const [{ isOver }, drop] = useDrop({
accept: ItemTypes.CARD,
drop: (item, monitor) => {
// Important: Check if we already handled the drop
// (useful for nested drop targets)
if (monitor.didDrop()) return;
moveCard(item.id, item.sourceColumnId, id);
},
collect: (monitor) => ({
isOver: monitor.isOver({ shallow: true }),
}),
});
// Attach the drop ref
drop(ref);
return (
<div
ref={ref}
style={{
...styles.column,
...(isOver ? styles.columnActive : {}),
}}
>
<h3 style={{ borderBottom: '1px solid #ccc', paddingBottom: '10px' }}>
{title}
</h3>
{cards.map((card) => (
<Card
key={card.id}
id={card.id}
text={card.text}
columnId={id}
moveCard={moveCard}
/>
))}
</div>
);
};
// --- 5. Main Board Logic ---
const KanbanBoard = () => {
// Initial State: Dictionary of Columns containing arrays of Cards
const [boardData, setBoardData] = useState({
'todo': {
title: 'To Do',
cards: [
{ id: '1', text: 'Research Market Trends' },
{ id: '2', text: 'Design System Setup' },
{ id: '3', text: 'Write Unit Tests' },
],
},
'in-progress': {
title: 'In Progress',
cards: [{ id: '4', text: 'Develop Login API' }],
},
'done': {
title: 'Done',
cards: [{ id: '5', text: 'Project Kickoff Meeting' }],
},
});
/**
* Complex Logic: Handles moving a card between lists immutably.
*
* @param {string} cardId - The ID of the card being moved
* @param {string} sourceId - The column ID the card came from
* @param {string} targetId - The column ID the card is dropped into
*/
const moveCard = useCallback((cardId, sourceId, targetId) => {
setBoardData((prev) => {
// 1. If dropping in the same place, do nothing
if (sourceId === targetId) return prev;
// 2. Find the card object in the source list
const sourceCards = prev[sourceId].cards;
const cardIndex = sourceCards.findIndex((c) => c.id === cardId);
const cardToMove = sourceCards[cardIndex];
if (!cardToMove) return prev;
// 3. Create new state immutably
return {
...prev,
// Remove from source
[sourceId]: {
...prev[sourceId],
cards: sourceCards.filter((_, idx) => idx !== cardIndex),
},
// Add to target
[targetId]: {
...prev[targetId],
cards: [...prev[targetId].cards, cardToMove],
},
};
});
}, []);
return (
<div style={styles.container}>
{Object.keys(boardData).map((key) => {
const column = boardData[key];
return (
<Column
key={key}
id={key}
title={column.title}
cards={column.cards}
moveCard={moveCard}
/>
);
})}
</div>
);
};
// --- 6. App Entry Point ---
// The DndProvider must wrap the top-level component using the backend
const App = () => {
return (
<DndProvider backend={HTML5Backend}>
<KanbanBoard />
</DndProvider>
);
};
export default App;
Key Concepts Used
1. The Hooks Architecture
React DnD relies heavily on hooks.
useDrag: Used inside the Card component. It returns a ref (to attach to the DOM node) and isDragging (boolean state). We define the item payload here (ID and source column) so the drop zone knows what is being dropped.
useDrop: Used inside the Column component. It specifies accept: ItemTypes.CARD (acting as a contract to only accept specific drags). The drop function triggers the state update logic.
2. The DndProvider
At the root level (App), we wrap the application in <DndProvider backend={HTML5Backend}>. This injects a context containing the drag-and-drop manager into the React tree. Without this, the hooks useDrag and useDrop cannot communicate with each other.
3. Immutable State Updates
The moveCard function demonstrates complex React state management. Because our state is a nested object (Columns -> Cards), we cannot simply use .push() or .splice(). We must:
- Create a shallow copy of the state object.
- Filter out the card from the source column array.
- Append the card to the target column array.
- Return the new object to trigger a re-render.
4. Visual Feedback
- Drag Source: We use
isDragging to apply opacity and a slight rotation to the card currently being dragged.
- Drop Target: We use
isOver to change the background color of the column when a valid card hovers over it. This is crucial for User Experience (UX) so the user knows where they can drop the item.