Skip to content

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 the threshold, not classified as a swipe.
ts
export type SwipeDirection = "up" | "right" | "down" | "left" | "none";

UseSwipeProps ​

Props for the useSwipe hook.

PropertyTypeRequiredDescription
targetRefObject<Element> \| Element✓The element to attach swipe detection to. Accepts a RefObject or a direct element reference.
onSwipeStart(e: MouseEvent \| TouchEvent) => voidCalled when a swipe gesture begins (first pointerdown / touchstart).
onSwipe(e: MouseEvent \| TouchEvent, direction: SwipeDirection, delta: { x: number; y: number }) => voidCalled during an active swipe gesture on each move event.
onSwipeEnd(e: MouseEvent \| TouchEvent, direction: SwipeDirection, delta: { x: number; y: number }) => voidCalled 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.

InputInput DescriptionReturnReturn Description
()The function returned by useSwipe that stops all swipe event listeners. Call it to manually clean up before unmount if needed.void;

Released under the MIT License.