All hooks / Events and input
useSwipe
Calls onSwipe with 'left', 'right', 'up', or 'down' when the user swipes on an element, with touch, pen, or mouse. Returns a callback ref.
Uses pointer events, so one handler covers every input. The direction is the axis that moved most. Too short or too slow and it isn't a swipe.
Set CSS touch-action on the element so the browser doesn't take the gesture for scrolling: pan-y for horizontal swipes, pan-x for vertical, none for both.
Import
import { useSwipe } from '@vincent.ri/react-tils'
// or only this hook
import { useSwipe } from '@vincent.ri/react-tils/useSwipe'Usage
const ref = useSwipe<HTMLDivElement>((direction) => {
if (direction === 'left') next()
if (direction === 'right') previous()
})
return <div ref={ref} style={{ touchAction: 'pan-y' }}><Slide /></div>Live demo
Swipe or drag across the box.
When to use it
Swiping between carousel slides, dismissing a card or notification, or closing a drawer with a swipe.
When not to
You need the element to follow the finger while dragging; use useDrag. For scrolling between items, CSS scroll snap (scroll-snap-type) needs no JS. Swipes must have a button or keyboard alternative.
API
function useSwipe<T extends HTMLElement = HTMLElement>(onSwipe: (direction: SwipeDirection, event: PointerEvent) => void, options?: SwipeOptions): (element: T | null) => void| Parameter | Description |
|---|---|
onSwipe | Called with the direction and the pointerup event. Can change every render. |
options | threshold and maxDurationMs. Optional. |
Returns A callback ref. Pass it to the element's ref prop.
Types
export type SwipeDirection = "left" | "right" | "up" | "down";
export type SwipeOptions = {
/** Minimum distance in pixels. Default `50`. */
threshold?: number;
/** Maximum duration in milliseconds; slower drags aren't swipes. Default `800`. */
maxDurationMs?: number;
};Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| Pointer eventsWidely available | 55+ | 12+ | 59+ | 13+ | 55+ | 13+ |
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).