useSwipe
Hook to handle swipe gesture. See demo
Demo
INFO
The component uses useSwipe hook to handle swipe event on a div element.
Loading demo…
Show source code
tsx
import { useRef } from "react";
import { useSwipe } from "../../../..";
export const UseSwipe = () => {
const divRef = useRef<HTMLDivElement>(null);
useSwipe({
target: divRef,
onSwipe(_, direction, delta) {
console.log(direction)
delta.x >=0 && (divRef.current!.style.left = delta.x + "px");
},
onSwipeEnd(_, __, delta) {
divRef.current!.style.left = `${delta.x>330 ? "400" : "0"}px`
},
});
const reset = () => {
divRef.current!.style.left = "0";
}
return <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "center", width: 400, height: 100, border: "1px solid lightgray", overflow: "hidden", margin: "0 auto" }}>
<button onClick={reset}>RESET</button>
<div ref={divRef} style={{ position: "absolute", backgroundColor: "rgb(73 84 104)", zIndex: 100, inset: 0 }}><p>SWIPE</p></div>
</div>
}Types
SwipeDirection
Detected swipe direction returned by useSwipe callbacks.
"up"/"down"— vertical swipes."left"/"right"— horizontal swipes."none"— movement below thethreshold, not classified as a swipe.
ts
export type SwipeDirection = "up" | "right" | "down" | "left" | "none";UseSwipeProps
Props for the useSwipe hook.
| Property | Type | Required | Description |
|---|---|---|---|
target | RefObject<Element> \| Element | ✓ | The element to attach swipe detection to. Accepts a RefObject or a direct element reference. |
onSwipeStart | (e: MouseEvent \| TouchEvent) => void | Called when a swipe gesture begins (first pointerdown / touchstart). | |
onSwipe | (e: MouseEvent \| TouchEvent, direction: SwipeDirection, delta: { x: number; y: number }) => void | Called during an active swipe gesture on each move event. | |
onSwipeEnd | (e: MouseEvent \| TouchEvent, direction: SwipeDirection, delta: { x: number; y: number }) => void | Called when the swipe gesture ends (pointer released / touchend). | |
options | { passive?: boolean; threshold?: number; } | Listener and gesture threshold configuration. |
UseSwipeResult
The function returned by useSwipe that stops all swipe event listeners. Call it to manually clean up before unmount if needed.
| Input | Input Description | Return | Return Description |
|---|---|---|---|
() | The function returned by useSwipe that stops all swipe event listeners. Call it to manually clean up before unmount if needed. | void; |
