ilias-use-long-press
v1.0.0
Published
A lightweight React hook for triggering actions after a long press on buttons and pressable elements.
Maintainers
Readme
ilias-use-long-press
A lightweight React hook for firing an action only after a button or pressable element has been held down long enough.
Installation
npm install ilias-use-long-pressUsage
import { useLongPress } from "ilias-use-long-press";
function DeleteButton() {
const { onMouseDown, onMouseUp, onMouseLeave, isLongPressing } = useLongPress(() => {
console.log("Long press triggered");
}, {
delay: 600,
repeat: false,
});
return (
<button
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
onMouseLeave={onMouseLeave}
aria-pressed={isLongPressing}
>
{isLongPressing ? "Holding..." : "Press and hold"}
</button>
);
}API
useLongPress(callback, options?)
const {
isLongPressing,
onMouseDown,
onMouseUp,
onMouseLeave,
onTouchStart,
onTouchEnd,
onTouchCancel,
} = useLongPress(onLongPress, {
delay: 500,
disabled: false,
shouldPreventDefault: true,
repeat: false,
repeatDelay: 500,
onStart: () => undefined,
onFinish: () => undefined,
onCancel: () => undefined,
});Options
delay— number of milliseconds before triggering the long press. Default:500.disabled— disables the interaction whentrue.shouldPreventDefault— prevents default pointer behavior while the press is active. Default:true.repeat— whether the callback should fire repeatedly while pressed. Default:false.repeatDelay— interval used between repeating callbacks. Default: same asdelay.onStart— called once when the press begins.onFinish— called when the press ends or is canceled.onCancel— called when the press is canceled before the long press fires.
Return value
isLongPressing— whether the press is currently active.onMouseDown— bind to the mouse down event.onMouseUp— bind to the mouse up event.onMouseLeave— bind to the mouse leave event.onTouchStart— bind to the touch start event.onTouchEnd— bind to the touch end event.onTouchCancel— bind to the touch cancel event.
Typical use cases
- Delete actions that require a hold gesture
- Repeated actions like volume or brightness controls
- Long-press actions for mobile and desktop buttons
Notes
- The timer is cleaned up on unmount.
- The callback is canceled automatically when the pointer is released or leaves the element.
- Repeating long press is optional and can be enabled with
repeatandrepeatDelay.
npm install
npm testCreate a production build with:
npm run buildContributing
See CONTRIBUTING.md for branch and commit conventions. Contributions are expected to include tests when they change behavior.
License
This project is licensed under the ISC License.
