Skip to main content
Version: Next

useDrag

This hook provides a way to make any HTMLElement draggable.

Arguments

callback [ function ]

First argument is a callback function with a drag event object as its first argument which is called on every drag event.

Here are the properties of an event object argument of a callback function:

PropertyDescription
argsArray of argument passed in bind function.
downBoolean indicating the mouse click state.
movementXAmount of movement in x-axis. Always starts from 0 while dragging.
movementYAmount of movement in y-axis. Always starts from 0 while dragging.
offsetXAmount of movement with offset in x-axis. It saves the previous movement and drag starts from previous position.
offsetYAmount of movement with offset in y-axis. It saves the previous movement and drag starts from previous position.
velocityXVelocity along horizontal drag direction.
velocityYVelocity along vertical drag direction.
directionXIndicates the current horizontal drag direction. For positive +1, for negative -1 and for not dragging 0.
directionYIndicates the current vertical drag direction. For positive +1, for negative -1 and for not dragging 0.
distanceXSame as movementX but always positive.
distanceYSame as movementY but always positive.
cancelFunction to cancel the current drag gesture.

config [ object ]

The second argument is an optional object which is called every time on mouse / pointer down event.

OptionsDefaultDescription
initialundefinedFunction called initially on mouse / pointer down. It must return an object with movementX and movementY properties.

Returns

It returns a function which is spread on any HTMLELement.

Define a bind function:

const bind = useDrag((event) => doSomething(event));

Apply it on a HTMLELement:

<div {...bind()} style={{ width: 100, height: 100, backgroundColor: 'red' }} />

Example

In the below example, useDrag hook is used to make a HTMLElement draggable.

import { useAnimatedValue, useDrag, animate } from 'react-ui-animate';

export default function () {
const left = useAnimatedValue(0);

const bind = useDrag(function ({ offsetX }) {
left.value = offsetX;
});

return (
<animate.div
{...bind()} // bind here
style={{
width: 100,
height: 100,
backgroundColor: '#3399ff',
position: 'absolute',
left: left.value,
top: 0,
}}
/>
);
}