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.
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/reactVanilla JavaScript
# Yarn
yarn add @use-gesture/vanilla
# NPM
npm install @use-gesture/vanillaEffect 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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
