react-usehooks-ts
Version:
A collections of typescript supported react Custom hooks
47 lines (46 loc) • 1.82 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const useSwipe = (SWIPE_THRESHOLD = 60) => {
const [swipeDirection, setSwipeDirection] = (0, react_1.useState)(null);
const swipeRef = (0, react_1.useRef)(null);
const touchStartX = (0, react_1.useRef)(null);
const touchEndX = (0, react_1.useRef)(null);
(0, react_1.useEffect)(() => {
const handleTouchStart = (e) => {
touchStartX.current = e.touches[0].clientX;
};
const handleTouchMove = (e) => {
touchEndX.current = e.touches[0].clientX;
};
const handleTouchEnd = () => {
if (touchStartX.current !== null && touchEndX.current !== null) {
const deltaX = touchEndX.current - touchStartX.current;
if (deltaX > SWIPE_THRESHOLD) {
setSwipeDirection('right');
}
else if (deltaX < -SWIPE_THRESHOLD) {
setSwipeDirection('left');
}
else {
setSwipeDirection(null);
}
}
};
const element = swipeRef.current;
if (element) {
element.addEventListener('touchstart', handleTouchStart);
element.addEventListener('touchmove', handleTouchMove);
element.addEventListener('touchend', handleTouchEnd);
}
return () => {
if (element) {
element.removeEventListener('touchstart', handleTouchStart);
element.removeEventListener('touchmove', handleTouchMove);
element.removeEventListener('touchend', handleTouchEnd);
}
};
}, []);
return [swipeDirection, swipeRef];
};
exports.default = useSwipe;
;