Skip to content

React DnD Custom Preview Not Showing — Fix Drag Layer

DodaTech Updated 2026-06-24 1 min read

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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What is the purpose of a drag layer in React DnD?

The drag layer is a separate component that renders the drag preview on top of everything. It uses useDragLayer to access the current drag state and renders a custom preview.

How do I hide the default ghost preview?

Set opacity: 0 on the dragged element during drag. The drag layer handles showing the custom preview.

What data does useDragLayer expose?

itemType (drag type), item (dragged data), currentOffset (mouse position), isDragging (boolean), initialOffset (position where drag started).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro