Appearance
useSwipe
Reactive swipe detection based on TouchEvents
Demo
Usage
tsx
import { useSwipe } from '@reause/core'
import { useRef } from 'react'
function Demo() {
const el = useRef<HTMLDivElement>(null)
const { isSwiping, direction } = useSwipe(el)
return (
<div ref={el}>
Swipe here
</div>
)
}target is a React ref object (RefObject) holding the element — bind it to the element you want to listen on (a useRef that is not attached to any node listens to nothing). The resolved element is re-read after every commit, so a ref that is still null while rendering binds as soon as React attaches the element.
Options
passive(boolean, defaulttrue): register the touch listeners as passive. Whenfalse, the listeners are registered withcapture: trueand a horizontaltouchmovecallspreventDefault().threshold(number, default50): minimummax(|dx|, |dy|)in pixels before a touch counts as a swipe.onSwipeStart((e: TouchEvent) => void): called ontouchstartwith a single touch point.onSwipe((e: TouchEvent) => void): called ontouchmovewhile a swipe is in progress.onSwipeEnd((e: TouchEvent, direction: UseSwipeDirection) => void): called ontouchend/touchcancelonce the threshold was crossed, with the final direction.
Return Values
isSwiping(boolean): whether a swipe is currently in progress.direction('up' | 'down' | 'left' | 'right' | 'none'): swipe direction derived from the start and end coordinates;'none'below the threshold.coordsStart/coordsEnd({ x: number, y: number }): start and last touch coordinates.lengthX/lengthY(number):coordsStart.x - coordsEnd.x/coordsStart.y - coordsEnd.y.stop(() => void): permanently detach the listeners for this hook instance.
Type Declarations
ts
export type UseSwipeDirection = 'up' | 'down' | 'left' | 'right' | 'none'
export interface UseSwipeOptions extends ConfigurableWindow {
passive?: boolean;
threshold?: number;
onSwipeStart?: (e: TouchEvent) => void;
onSwipe?: (e: TouchEvent) => void;
onSwipeEnd?: (e: TouchEvent, direction: UseSwipeDirection) => void;
}
export interface UseSwipeReturn {
isSwiping: boolean;
direction: UseSwipeDirection;
coordsStart: Readonly<Position>;
coordsEnd: Readonly<Position>;
lengthX: number;
lengthY: number;
stop: () => void;
}
interface Position {
x: number;
y: number;
}
export function useSwipe(target: RefObject<EventTarget | null | undefined>, options?: UseSwipeOptions): UseSwipeReturn