useLongPress
Recognizes long-press gestures with delay control.
Recognizes long-press gestures with delay control.
Import
import { useLongPress } from '@kamod-ch/hooks'Live demo
Basic demo
Recognizes long-press gestures with delay control.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useLongPress } from '@kamod-ch/hooks'
export default function UseLongPressDemo() {
const ref = useRef<HTMLButtonElement>(null)
const [count, setCount] = useState(0)
useLongPress(() => setCount((value) => value + 1), ref, { delay: 600 })
return (
<div>
<button ref={ref} type="button">Press and hold me</button>
<p><strong>Long presses:</strong> {count}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type EventType = MouseEvent | TouchEvent;
export interface Options {
delay?: number;
moveThreshold?: {
x?: number;
y?: number;
};
onClick?: (event: EventType) => void;
onLongPressEnd?: (event: EventType) => void;
}
declare function useLongPress(onLongPress: (event: EventType) => void, target: BasicTarget, { delay, moveThreshold, onClick, onLongPressEnd }?: Options): void;
export default useLongPress;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.