reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
39 lines (38 loc) • 1.58 kB
JavaScript
import { useRef, useState, useEffect } from "react";
export function useSwipe(options = { threshold: 50 }) {
const ref = useRef(null);
const [direction, setDirection] = useState(null);
const startPos = useRef(null);
useEffect(() => {
const element = ref.current;
if (!element)
return;
const handleTouchStart = (e) => {
const touch = e.touches[0];
startPos.current = { x: touch.clientX, y: touch.clientY };
};
const handleTouchEnd = (e) => {
if (!startPos.current)
return;
const touch = e.changedTouches[0];
const deltaX = touch.clientX - startPos.current.x;
const deltaY = touch.clientY - startPos.current.y;
if (Math.abs(deltaX) > Math.abs(deltaY) &&
Math.abs(deltaX) > options.threshold) {
setDirection(deltaX > 0 ? "right" : "left");
}
else if (Math.abs(deltaY) > options.threshold) {
setDirection(deltaY > 0 ? "down" : "up");
}
setTimeout(() => setDirection(null), 0); // Reset direction after detection
startPos.current = null;
};
element.addEventListener("touchstart", handleTouchStart);
element.addEventListener("touchend", handleTouchEnd);
return () => {
element.removeEventListener("touchstart", handleTouchStart);
element.removeEventListener("touchend", handleTouchEnd);
};
}, [options.threshold]);
return [ref, direction];
}