Hook that makes a DOM element draggable.
✓ Published0🌍 Public
Aabonello
Last edited Jul 6, 2021
Created on Dec 30, 2021
This example shows a React hook that makes any DOM element draggable by handling mouse events. The hook returns a ref to attach to the target element and a mouse-down handler; when the user presses and drags, it computes the new position from the initial click offset and calls a provided `onMove` callback with the updated coordinates. It uses React’s `useRef`, `useState`, `useEffect`, and `useCallback`, attaching global `mousemove` and `mouseup` listeners while dragging. The code relies on `getBoundingClientRect` to calculate the offset, enabling smooth, frame-accurate movement without external libraries.
AI-generated description