use-gesture

Bread n butter utility for component-tied mouse/touch gestures in React and...

README

@use-gesture

npm (tag) npm bundle size NPM Discord Shield

@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


  1. ``` sh
  2. #Yarn
  3. yarn add @use-gesture/react

  4. #NPM
  5. npm install @use-gesture/react
  6. ```

Vanilla javascript


  1. ``` sh
  2. #Yarn
  3. yarn add @use-gesture/vanilla

  4. #NPM
  5. npm install @use-gesture/vanilla
  6. ```


- FAQ

Simple example


React

  1. ``` js
  2. import { useSpring, animated } from '@react-spring/web'
  3. import { useDrag } from '@use-gesture/react'

  4. function Example() {
  5.   const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))

  6.   // Set the drag hook and define component movement based on gesture data.
  7.   const bind = useDrag(({ down, movement: [mx, my] }) => {
  8.     api.start({ x: down ? mx : 0, y: down ? my : 0 })
  9.   })

  10.   // Bind it to a component.
  11.   return <animated.div {...bind()} style={{ x, y, touchAction: 'none' }} />
  12. }
  13. ```

Vanilla javascript

  1. ``` html
  2. <div id="drag" />
  3. ```

  1. ``` js
  2. // script.js
  3. const el = document.getElementById('drag')
  4. const gesture = new DragGesture(el, ({ active, movement: [mx, my] }) => {
  5.   setActive(active)
  6.   anime({
  7.     targets: el,
  8.     translateX: active ? mx : 0,
  9.     translateY: active ? my : 0,
  10.     duration: active ? 0 : 1000
  11.   })
  12. })

  13. // when you want to remove the listener
  14. gesture.destroy()
  15. ```


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](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) 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:

HookDescription
------------------------------------------------------
`useDrag`Handles
`useMove`Handles
`useHover`Handles
`useScroll`Handles
`useWheel`Handles
`usePinch`Handles
`useGesture`Handles