Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created April 6, 2019 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabemeola/54bb25fa4324f3224c36793c2d37205a to your computer and use it in GitHub Desktop.
Save gabemeola/54bb25fa4324f3224c36793c2d37205a to your computer and use it in GitHub Desktop.
Use Long Press Effect
import React, { useEffect } from 'react';
export default function useLongPress(onLongPress: (ev: React.TouchEvent) => any, touchDuration: number = 500) {
let timer: NodeJS.Timeout;
const startTimer = (ev: React.TouchEvent) => {
// Re-assigning event so we can keep a ref if react cleans up
// (https://reactjs.org/docs/events.html#event-pooling)
const event = ev;
timer = setTimeout(() => onLongPress(event), touchDuration);
}
const clearTimer = () => {
if (timer) clearTimeout(timer);
}
useEffect(() => {
// Clear timeout on component unmount
return clearTimer;
}, [])
const style: React.CSSProperties = {
// TODO: Only disable userSelect on startTimer
userSelect: 'none',
WebkitTouchCallout: 'none'
}
return {
// Prevent Content Menus
// TODO: Allow contextMenu on mouse devices
onContextMenu: (ev: React.MouseEvent) => ev.preventDefault(),
onTouchStart: startTimer,
onTouchEnd: clearTimer,
onTouchMove: clearTimer,
style,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment