React DnD Custom Preview Not Showing — Fix Drag Layer
In this fix, you'll learn how to create a custom drag preview in React DnD. This matters for visual feedback during drag operations, and appears in kanban boards and sortable lists.
The Problem
The following code demonstrates the typical mistake:
const [{ isDragging }, drag] = useDrag(() => ({
type: 'ITEM',
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
}));
return <div ref={drag}>Item</div>;
// Default ghost preview appears instead of custom one
The Fix
Here is the corrected version:
function CustomDragLayer() {
const { itemType, item, currentOffset } = useDragLayer((monitor) => ({
itemType: monitor.getItemType(),
item: monitor.getItem(),
currentOffset: monitor.getSourceClientOffset(),
}));
if (!currentOffset) return null;
return (
<div style={{
position: 'fixed', pointerEvents: 'none',
left: currentOffset.x, top: currentOffset.y,
}}>
<CustomPreview data={item} />
</div>
);
}
// Custom preview follows cursor during drag
Prevention
- Create a separate DragLayer component using useDragLayer.
- Use monitor.getSourceClientOffset() for preview position.
- Set pointerEvents: 'none' on the drag layer.
- Hide the dragged element during drag (opacity) while the layer shows the preview.
- Render the drag layer with position: fixed and high z-index.
Common Mistakes with dnd preview
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
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