Search code examples
javascriptreactjsdrag-and-dropdraggablereact-dnd

How to get realtime coordinates with React DnD


react-dnd library for ReactJS provides begin and end callbacks for dragging. However, I can't find a way in the docs to access the drag event that fires while a drag is in progress. What would be the correct way to access this event in a component that uses react-dnd?

I want real time feedback so I can display the coordinates of a drag in progress.

Expected:

function Draggable({ onDrag, children }) {
  const [, drag] = useDrag({
    item: { id, type },
    onDrag, // this is not available in react-dnd
  })

  return <div ref={drag}>{children}</div>
}

Solution

  • You can get realtime coordinates through DragLayerMonitor.

    Check the document DragLayerMonitor and the custom drag layer example.

    I've made a slider component in this way and it works well for me. I made it a codepen, but I don't know how to post codepen link here. Anyway, I believe you will figure it out, that custom drag layer example helped me a lot.