Getting started
👆 @use-gesture is a set of gestures that let you bind mouse and touch events to any node.
With the data you receive, it becomes easy to set up complex gestures like dragging and pinching with a few lines of code.
React
In React, 👆 @use-gesture/react consists in multiple hooks you can attach to a component. You can use the library as standalone, but to make the most of it you should combine it with an animation library like react-spring.
Installation
yarn add @use-gesture/reactnpm install @use-gesture/react
Simple React 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.
import { useSpring, animated } from '@react-spring/web'import { useDrag } from '@use-gesture/react'function PullRelease() {const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))// Set the drag hook and define component movement based on gesture dataconst bind = useDrag(({ down, movement: [mx, my] }) => {api.start({ x: down ? mx : 0, y: down ? my : 0, immediate: down })})// Bind it to a componentreturn <animated.div {...bind()} style={{ x, y }} />}
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 onPointerDown
, onPointerMove
and onPointerUp
event handlers (the handlers may vary depending on the configuration options passed to useDrag
).
It's important that you understand 👆 @use-gesture/react 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.
Vanilla javascript
Although 👆 @use-gesture was originally built for React, v10 is now platform agnostic, and can work in vanilla javascript.
Installation
yarn add @use-gesture/vanillanpm install @use-gesture/vanilla
Simple Vanilla 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.
<!-- index.html --><div id="drag" />
// script.jsconst el = document.getElementById('drag')const gesture = new DragGesture(el, ({ active, movement: [mx, my] }) => {setActive(active)anime({targets: el,translateX: active ? mx : 0,translateY: active ? my : 0,duration: active ? 0 : 1000})})// when you want to remove the listenergesture.destroy()
The vanilla api is new from v10 and still experimental. Feel free to contribute!