react-long-press-hook
Version:
Unlock the power of long-press interactions with react-press-and-hold! 🚀 This lightweight and highly customizable React hook lets you easily detect and handle long-press events in your applications. Whether you’re looking to enhance your UI with context
66 lines (63 loc) • 2.46 kB
JavaScript
import { useRef, useCallback } from 'react';
// import { useCallback, useRef } from "react";
const useLongPress = (callback, { onStart = () => { }, onFinish = () => { }, threshold = 300, preventDefault = true, cancelOnMove = false, stopPropagation = false, } = {}) => {
const timerRef = useRef(null);
const startX = useRef(null);
const startY = useRef(null);
const start = useCallback((event) => {
if (preventDefault && event.target) {
event.target.addEventListener("contextmenu", (e) => e.preventDefault());
}
if (stopPropagation) {
event.stopPropagation();
}
if (event instanceof MouseEvent) {
startX.current = event.clientX;
startY.current = event.clientY;
}
else if (event.touches && event.touches.length > 0) {
startX.current = event.touches[0].clientX;
startY.current = event.touches[0].clientY;
}
onStart(event);
timerRef.current = setTimeout(() => {
callback(event);
}, threshold);
}, [callback, onStart, preventDefault, stopPropagation, threshold]);
const stop = useCallback((event, shouldTriggerCallback = true) => {
if (preventDefault && event.target) {
event.target.removeEventListener("contextmenu", (e) => e.preventDefault());
}
clearTimeout(timerRef.current);
if (shouldTriggerCallback) {
onFinish(event);
}
}, [onFinish, preventDefault]);
const move = useCallback((event) => {
if (cancelOnMove) {
let dx = 0;
let dy = 0;
if (event instanceof MouseEvent) {
dx = Math.abs(event.clientX - startX.current);
dy = Math.abs(event.clientY - startY.current);
}
else if (event.touches && event.touches.length > 0) {
dx = Math.abs(event.touches[0].clientX - startX.current);
dy = Math.abs(event.touches[0].clientY - startY.current);
}
if (dx > 10 || dy > 10) {
stop(event, false);
}
}
}, [cancelOnMove, stop]);
const handlers = {
onMouseDown: start,
onTouchStart: start,
onMouseUp: (event) => stop(event),
onTouchEnd: (event) => stop(event),
onTouchMove: move,
onMouseMove: move,
};
return handlers;
};
export { useLongPress };