@use-gesture is a library that lets you bind richer mouse and touch events to any component or view. With the data you receive, it becomes trivial to set up gestures, and often takes no more than a few lines of code.
You can use it stand-alone, but to make the most of it you should combine it with an animation library like react-spring, though you can most certainly use any other.
import{useSpring,animated}from'@react-spring/web'import{useDrag}from'@use-gesture/react'functionExample(){const[{ x, y },api]=useSpring(()=>({x: 0,y: 0}))// Set the drag hook and define component movement based on gesture data.constbind=useDrag(({ down,movement: [mx,my]})=>{api.start({x: down ? mx : 0,y: down ? my : 0})})// Bind it to a component.return<animated.div{...bind()}style={{ x, y,touchAction: 'none'}}/>}
Vanilla javascript
<!-- index.html --><divid="drag" />
// script.jsconstel=document.getElementById('drag')constgesture=newDragGesture(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 example above makes a div draggable so that it follows your mouse on drag, and returns to its initial position on release.
Make sure you always set touchAction on a draggable element to prevent glitches with the browser native scrolling on touch devices.
Available hooks
@use-gesture/react exports several hooks that can handle different gestures:
pmndrs/use-gesture
@use-gesture
@use-gesture is a library that lets you bind richer mouse and touch events to any component or view. With the data you receive, it becomes trivial to set up gestures, and often takes no more than a few lines of code.
You can use it stand-alone, but to make the most of it you should combine it with an animation library like react-spring, though you can most certainly use any other.
The demos are real click them!
Installation
React
Vanilla javascript
Full documentation website
Simple example
React
Vanilla javascript
The example above makes a
div
draggable so that it follows your mouse on drag, and returns to its initial position on release.Make sure you always set
touchAction
on a draggable element to prevent glitches with the browser native scrolling on touch devices.Available hooks
@use-gesture/react exports several hooks that can handle different gestures:
useDrag
useMove
useHover
useScroll
useWheel
usePinch
useGesture
More on the full documentation website...