use-gesture
👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
Top Related Projects
👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
React swipe event handler hook
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️
Beautiful and accessible drag and drop for lists with React
A modern animation library for React and JavaScript
Quick Overview
use-gesture is a React hook library for adding gesture interactions to your applications. It provides a simple and intuitive way to handle mouse, touch, and pointer events, allowing developers to create rich, interactive user interfaces with minimal code.
Pros
- Easy to use and integrate into existing React projects
- Supports a wide range of gestures, including drag, pinch, scroll, wheel, and more
- Highly customizable with options for fine-tuning gesture behavior
- Works well with animation libraries like react-spring for smooth transitions
Cons
- Limited to React applications, not usable in vanilla JavaScript or other frameworks
- May have a slight learning curve for developers new to gesture-based interactions
- Performance might be impacted in complex applications with many gesture handlers
- Documentation could be more comprehensive for advanced use cases
Code Examples
- Basic drag gesture:
import { useDrag } from '@use-gesture/react'
function DraggableBox() {
const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))
const bind = useDrag(({ offset: [ox, oy] }) => api.start({ x: ox, y: oy }))
return <animated.div {...bind()} style={{ x, y }} />
}
- Pinch gesture for zooming:
import { usePinch } from '@use-gesture/react'
function ZoomableImage() {
const [{ scale }, api] = useSpring(() => ({ scale: 1 }))
const bind = usePinch(({ offset: [d] }) => api.start({ scale: d / 200 + 1 }))
return <animated.img {...bind()} style={{ scale }} />
}
- Combining multiple gestures:
import { useGesture } from '@use-gesture/react'
function InteractiveElement() {
const [state, api] = useSpring(() => ({ x: 0, y: 0, scale: 1 }))
const bind = useGesture({
onDrag: ({ offset: [ox, oy] }) => api.start({ x: ox, y: oy }),
onPinch: ({ offset: [d] }) => api.start({ scale: d / 200 + 1 })
})
return <animated.div {...bind()} style={state} />
}
Getting Started
To start using use-gesture in your React project:
-
Install the library:
npm install @use-gesture/react
-
Import and use the desired gesture hook in your component:
import { useDrag } from '@use-gesture/react' import { useSpring, animated } from 'react-spring' function MyComponent() { const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 })) const bind = useDrag(({ offset: [ox, oy] }) => api.start({ x: ox, y: oy })) return <animated.div {...bind()} style={{ x, y }}>Drag me!</animated.div> }
Competitor Comparisons
👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
Pros of use-gesture
- Comprehensive gesture support for React applications
- Highly customizable with a wide range of options
- Excellent documentation and examples
Cons of use-gesture
- Learning curve for complex gestures
- May be overkill for simple gesture needs
- Performance overhead for complex gesture combinations
Code Comparison
use-gesture:
const bind = useGesture({
onDrag: ({ offset: [x, y] }) => {
api.start({ x, y })
},
onPinch: ({ offset: [d, a] }) => {
api.start({ scale: d / 200 + 1, rotateZ: a })
}
})
Both repositories appear to be the same project, so there isn't a meaningful code comparison to make between them. The code example above demonstrates the usage of use-gesture for drag and pinch gestures.
Summary
use-gesture is a powerful and flexible gesture library for React applications. It offers comprehensive gesture support and high customizability, making it suitable for complex gesture-based interactions. However, it may have a steeper learning curve and potential performance overhead for simpler use cases. The library's extensive documentation and examples help mitigate the learning curve, making it a solid choice for developers needing advanced gesture support in their React projects.
React swipe event handler hook
Pros of react-swipeable
- Lightweight and focused specifically on swipe gestures
- Simple API with easy-to-use event handlers
- Good documentation with clear examples
Cons of react-swipeable
- Limited to swipe gestures only, less versatile than use-gesture
- Fewer customization options for advanced use cases
- Less active development and community support
Code Comparison
react-swipeable:
import { useSwipeable } from 'react-swipeable';
const handlers = useSwipeable({
onSwiped: (eventData) => console.log("User Swiped!", eventData),
...config,
});
return <div {...handlers}>Swipe me!</div>;
use-gesture:
import { useGesture } from '@use-gesture/react';
const bind = useGesture({
onDrag: ({ down, movement: [mx, my] }) => {
console.log("User dragged!", { down, mx, my });
},
});
return <div {...bind()}>Drag me!</div>;
react-swipeable is more straightforward for simple swipe gestures, while use-gesture offers a more comprehensive set of gesture handlers and greater flexibility. use-gesture supports a wider range of gestures and provides more detailed control over the gesture behavior, making it suitable for complex interactions. However, for projects that only require basic swipe functionality, react-swipeable may be a simpler and more lightweight option.
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️
Pros of react-sortable-hoc
- Specifically designed for sortable lists and grids in React
- Provides ready-to-use components for common sorting scenarios
- Includes built-in animations and drag handles
Cons of react-sortable-hoc
- Less flexible for general gesture handling
- Limited to sorting functionality
- May have a steeper learning curve for custom implementations
Code Comparison
react-sortable-hoc:
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
);
});
use-gesture:
import { useDrag } from '@use-gesture/react';
function DraggableItem({ children }) {
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, immediate: down });
});
return <div {...bind()} style={{ x, y }}>{children}</div>;
}
Beautiful and accessible drag and drop for lists with React
Pros of react-beautiful-dnd
- Specifically designed for drag-and-drop functionality in React applications
- Provides a more opinionated and structured approach to implementing drag-and-drop
- Offers built-in accessibility features and keyboard support
Cons of react-beautiful-dnd
- Limited to drag-and-drop interactions only
- Less flexible for custom gestures or advanced touch interactions
- Larger bundle size due to its comprehensive drag-and-drop solution
Code Comparison
react-beautiful-dnd:
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="list">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
use-gesture:
import { useDrag } from '@use-gesture/react';
const bind = useDrag(({ movement: [mx, my], down }) => {
setPosition({ x: down ? mx : 0, y: down ? my : 0 })
})
return <div {...bind()} style={{ transform: `translate(${x}px, ${y}px)` }} />
A modern animation library for React and JavaScript
Pros of Motion
- Simpler API with a more intuitive syntax for basic animations
- Built-in support for spring animations and keyframes
- Smaller bundle size, which can lead to better performance
Cons of Motion
- Less comprehensive gesture support compared to use-gesture
- Fewer advanced features for complex interactions
- Limited customization options for gesture behaviors
Code Comparison
Motion:
import { motion } from "framer-motion"
<motion.div
drag
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
/>
use-gesture:
import { useGesture } from '@use-gesture/react'
const bind = useGesture({
onDrag: ({ offset: [x, y] }) => set({ x, y }),
onHover: ({ hovering }) => set({ scale: hovering ? 1.1 : 1 }),
onPointerDown: () => set({ scale: 0.9 }),
onPointerUp: () => set({ scale: 1 })
})
<div {...bind()} style={{ x, y, scale }} />
Motion offers a more declarative approach with built-in animation properties, while use-gesture provides more granular control over gesture interactions. Motion is generally easier to use for simple animations, but use-gesture offers more flexibility for complex gesture-based interactions.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
@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
#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
Full documentation website
Simple example
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 }))
// Set the drag hook and define component movement based on gesture data.
const bind = 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 -->
<div id="drag" />
// 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()
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:
Hook | Description |
---|---|
useDrag | Handles the drag gesture |
useMove | Handles mouse move events |
useHover | Handles mouse enter and mouse leave events |
useScroll | Handles scroll events |
useWheel | Handles wheel events |
usePinch | Handles the pinch gesture |
useGesture | Handles multiple gestures in one hook |
More on the full documentation website...
Top Related Projects
👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
React swipe event handler hook
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️
Beautiful and accessible drag and drop for lists with React
A modern animation library for React and JavaScript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot