diff --git a/docs/useLongPress.md b/docs/useLongPress.md index 61e477bd14..59109166ca 100644 --- a/docs/useLongPress.md +++ b/docs/useLongPress.md @@ -33,14 +33,14 @@ const { onTouchEnd } = useLongPress( callback: (e: TouchEvent | MouseEvent) => void, - options: { - isPreventDefault: true, - delay: 300 + options?: { + isPreventDefault?: true, + delay?: 300 } ) ``` - `callback` — callback function. -- `options` — optional parameter. - - `isPreventDefault` — whether to call `event.preventDefault()` of `touchend` event, for preventing ghost click on mobile devices in some cases, defaults to `true`. - - `delay` — delay in milliseconds after which to calls provided callback, defaults to `300`. +- `options?` — optional parameter. + - `isPreventDefault?` — whether to call `event.preventDefault()` of `touchend` event, for preventing ghost click on mobile devices in some cases, defaults to `true`. + - `delay?` — delay in milliseconds after which to calls provided callback, defaults to `300`. diff --git a/src/useLongPress.ts b/src/useLongPress.ts index 7fc9621c8a..a1635b7169 100644 --- a/src/useLongPress.ts +++ b/src/useLongPress.ts @@ -5,8 +5,6 @@ interface Options { delay?: number; } -const DEFAULT_OPTIONS = { isPreventDefault: true, delay: 300 }; - const isTouchEvent = (event: Event): event is TouchEvent => { return 'touches' in event; }; @@ -19,28 +17,30 @@ const preventDefault = (event: Event) => { } }; -const useLongPress = (callback: (e: TouchEvent | MouseEvent) => void, options: Options = DEFAULT_OPTIONS) => { +const useLongPress = ( + callback: (e: TouchEvent | MouseEvent) => void, + { isPreventDefault = true, delay = 300 }: Options = {} +) => { const timeout = useRef>(); const target = useRef(); const start = useCallback( (event: TouchEvent | MouseEvent) => { // prevent ghost click on mobile devices - if (options.isPreventDefault && event.target) { - target.current = event.target; + if (isPreventDefault && event.target) { event.target.addEventListener('touchend', preventDefault, { passive: false }); + target.current = event.target; } - - timeout.current = setTimeout(() => callback(event), options.delay); + timeout.current = setTimeout(() => callback(event), delay); }, - [callback, options.delay] + [callback, delay] ); const clear = useCallback(() => { // clearTimeout and removeEventListener timeout.current && clearTimeout(timeout.current); - if (options.isPreventDefault && target.current) { + if (isPreventDefault && target.current) { target.current.removeEventListener('touchend', preventDefault); } }, []);