React DnD Drop Target Not Firing — Fix onDrop Handler
In this fix, you'll learn why onDrop doesn't fire in React DnD. This matters for building drag-and-drop interfaces, and appears in file organizers and task management boards.
The Problem
The following code demonstrates the typical mistake:
const [{ isOver }, drop] = useDrop(() => ({
accept: 'CARD', // Drag source uses 'ITEM'
drop: () => console.log('Dropped!'),
}));
// onDrop never fires — types don't match
The Fix
Here is the corrected version:
// Drag source:
const [, drag] = useDrag(() => ({ type: 'ITEM' }));
// Drop target:
const [{ isOver }, drop] = useDrop(() => ({
accept: 'ITEM', // Must match drag type
drop: (item, monitor) => {
console.log('Dropped:', item);
},
collect: (monitor) => ({
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
}),
}));
// onDrop fires correctly when item is dropped
Prevention
- Ensure accept type in useDrop matches exactly with drag source's type.
- Use monitor.isOver() and monitor.canDrop() for visual feedback.
- The drop handler receives (item, monitor).
- Use monitor.didDrop() to check if nested target handled the drop.
- Use canDrop to conditionally allow drops based on state.
Common Mistakes with dnd drop target
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro