Boost Your UI with use-gesture: Simple React & Vanilla JS Gestures

This article introduces the use-gesture library, a lightweight React and vanilla JavaScript tool for enriching mouse and touch interactions, explains installation via Yarn or npm, demonstrates various gesture hooks with code examples, and showcases visual effects through animated demos.

Programmer DD
Programmer DD
Programmer DD
Boost Your UI with use-gesture: Simple React & Vanilla JS Gestures

use-gesture

This is a React library that enriches mouse and touch gestures through event binding, requiring only a few simple lines of code.

Installation

React

# Yarn
yarn add @use-gesture/react

# NPM
npm install @use-gesture/react

Vanilla JavaScript

# Yarn
yarn add @use-gesture/vanilla

# NPM
npm install @use-gesture/vanilla

Effect Demo

Below are animated examples of the library in action:

Usage

React

import { useSpring, animated } from '@react-spring/web'
import { useDrag } from '@use-gesture/react'

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

  const bind = useDrag(({ down, movement: [mx, my] }) => {
    api.start({ x: down ? mx : 0, y: down ? my : 0 })
  })

  return <animated.div {...bind()} style={{ x, y, touchAction: 'none' }} />
}

Vanilla JavaScript

<!-- index.html -->
<div id="drag"></div>

// script.js
const 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 listener
gesture.destroy()

Different Hooks

useDrag

– handles drag gestures useMove – handles mouse movement events useHover – handles mouse enter and leave events useScroll – handles scroll events usePinch – handles pinch gestures useGesture – handles multiple gestures within a single hook

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptfrontend developmentReactgesture handlinguse-gesture
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.