useSwipe
Hook that tracks swipe gestures for touch and pointer events
sensors
low
test coverage
Last changed: 2 minutes ago
Installation
Library
CLI
Manual
typescript
import { useSwipe } from '@siberiacancode/reactuse';Usage
typescript
const swipe = useSwipe(ref, (value) => console.log(value.direction));
// or
const swipe = useSwipe<HTMLDivElement>((value) => console.log(value.direction));
// or
const swipe = useSwipe(ref);
// or
const swipe = useSwipe<HTMLDivElement>();Demo
Api
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| target | HookTarget | - | The target element to track swipe on |
| callback? | UseSwipeCallback | - | Swipe move callback |
Returns
UseSwipeReturn
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| callback? | UseSwipeCallback | - | Swipe move callback |
Returns
UseSwipeReturn & { ref: StateRef<Target> }
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| target | HookTarget | - | The target element to track swipe on |
| options? | UseSwipeOptions | - | Swipe options |
Returns
UseSwipeReturn
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| options? | UseSwipeOptions | - | Swipe options |
Returns
UseSwipeReturn & { ref: StateRef<Target> }
Type declaration
typescript
import type { HookTarget } from '@/utils/helpers';
import type { StateRef } from '../useRefState/useRefState';
export type SwipeDirection = 'down' | 'left' | 'none' | 'right' | 'up';
export type SwipeEvent = PointerEvent | TouchEvent;
export type UseSwipeCallback = (value: UseSwipeValue, event: SwipeEvent) => void;
export interface UseSwipeOptions {
/** Called when swipe moves */
onMove?: UseSwipeCallback;
/** Minimal distance in px to resolve direction */
threshold?: number;
/** Called when swipe ends */
onEnd?: (value: UseSwipeValue, event: SwipeEvent) => void;
/** Called when swipe starts */
onStart?: (value: UseSwipeValue, event: SwipeEvent) => void;
}
export interface UseSwipeValue {
/** Current swipe direction */
direction: SwipeDirection;
/** Horizontal swipe length */
lengthX: number;
/** Vertical swipe length */
lengthY: number;
}
export interface UseSwipeReturn {
/** The latest swipe value snapshot */
snapshot: UseSwipeValue;
/** Is swipe currently active */
swiping: boolean;
/** Function to enable subscriptions and rerender on next updates */
watch: () => UseSwipeValue;
}
export interface UseSwipe {
(target: HookTarget, callback?: UseSwipeCallback): UseSwipeReturn;
(target: HookTarget, options?: UseSwipeOptions): UseSwipeReturn;
<Target extends Element>(
callback?: UseSwipeCallback,
target?: never
): UseSwipeReturn & {
ref: StateRef<Target>;
};
<Target extends Element>(
options?: UseSwipeOptions,
target?: never
): UseSwipeReturn & {
ref: StateRef<Target>;
};
}
interface Coords {
x: number;
y: number;
}Source
Source • DemoContributors
D