Search code examples
javascriptreactjsdrag-and-dropdraggablednd-kit

dnd-kit: drag relative to mouse pointer instead of draggable


Using @dnd-kit/core the default behavior is to have the dragged element (and the div within the DragOverlay) be dragged relative to its original position. If I click and drag the Draggable at some offset from the origin of the Draggable, it will move relative to its original position with an offset according to the distance I have dragged the pointer.

How can I instead have the dragged item "jump" to the location of the pointer? The dragged item should be located directly below the pointer instead of relative to the original position.


Solution

  • Snap cursor to center: install @dnd-kit/modifiers and pass snapCenterToCursor into DragOverlay:

    <DragOverlay modifiers={[snapCenterToCursor]}> <YourDraggableComponentCopy /> </DragOverlay>
    

    Collision detection: add collisionDetection={pointerWithin} prop to DndContext:

    <DndContext collisionDetection={pointerWithin}>...</DndContext>
    

    See the "Pointer within" docs for more info.