Getting started

👍 React UseGesture is a set of hooks that let you bind mouse and touch events to any React component.

With the data you receive, it becomes easy to set up complex gestures like dragging and pinching with a few lines of code. You can use this library stand-alone, but to make the most of it you should combine it with an animation library like React-spring.

Installation

Using yarn:

yarn add react-use-gesture

Using npm:

npm install --save react-use-gesture

Simple example

The following example makes a <div/> draggable so that it follows your mouse or finger on drag, and returns to its initial position on release.

All examples in this documentation use React-spring v9, that you can install with the next tag: react-spring@next. v9 api is more convenient and allows for more compact, less distracting code. The following example is the only one available with React-spring v8.

Using React Spring v9
import { useSpring, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'
function PullRelease() {
const [{ x, y }, set] = useSpring(() => ({ x: 0, y: 0 }))
// Set the drag hook and define component movement based on gesture data
const bind = useDrag(({ down, movement: [mx, my] }) => {
set({ x: down ? mx : 0, y: down ? my : 0 })
})
// Bind it to a component
return <animated.div {...bind()} style={{ x, y }} />
}
Using React Spring v8
import { useSpring, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'
function PullRelease() {
const [{ xy }, set] = useSpring(() => ({ xy: [0, 0] }))
// Set the drag hook and define component movement based on gesture data
const bind = useDrag(({ down, movement }) => {
set({ xy: down ? movement : [0, 0] })
})
// Bind it to a component
return (
<animated.div
{...bind()}
style={{
transform: xy.interpolate((x, y) => `translate3d(${x}px, ${y}px, 0)`),
}}
/>
)
}

How does this work?

The useDrag hook returns a function (stored in the bind constant), which when called returns an object with event handlers. Here, when you spread {...bind()} into a component, you're actually adding onMouseDown and onTouchStart event handlers.

It's important that you understand 🖖 React UseGesture is not responsible for actually moving the component. The useDrag hook just hands over gesture data to React-spring which sets the component transforms. If you're not familiar with React-spring, head over its documentation here.