https://github.com/technarts/react-use-hold
React Hook for Handling Long Button Presses
https://github.com/technarts/react-use-hold
click hook long-press react
Last synced: about 2 months ago
JSON representation
React Hook for Handling Long Button Presses
- Host: GitHub
- URL: https://github.com/technarts/react-use-hold
- Owner: technarts
- Created: 2023-08-11T11:45:59.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-08-21T12:06:45.000Z (almost 2 years ago)
- Last Synced: 2025-04-14T10:58:13.315Z (about 2 months ago)
- Topics: click, hook, long-press, react
- Language: TypeScript
- Homepage:
- Size: 150 KB
- Stars: 0
- Watchers: 5
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# React Hook for Handling Long Button Presses
Altough the title states "Button Presses", `useHold` can be used for any HTML element supporting `onclick` event. With `useHold` hook, you can make a function call on N'th millisecond of a mouse click, suppressing the normal click event.
## Installation
```bash
$ npm i @technarts/react-use-hold
```## Usage
Below code exemplifies a button that whose regular clicks are handled as well as long clicks up to `500ms`. It also demonstrates how to handle the release, which is fired at the end of the long click.
```typescript
import React from "react";
import { useHold } from "@technarts/react-use-hold";const App = () => {
const [clicked, setClicked] = React.useState(false)
const [clicking, setClicking] = React.useState(false)
const events = useHold({
ms: 500,
onClick: () => {
setClicked(true);
},
onHold: () => {
setClicking(true);
},
onRelease: () => {
setClicked(false);
setClicking(false);
},
})return (
<>
Click and keep clicking
Clicked: {clicked ? "Yes" : "No"}
Clicking: {clicking ? "Yes" : "No"}
>
)
}
```## Types
### `useHold(params: Params) => void`
```typescript
type Params = {
onClick?: React.MouseEventHandler, // This one will be called for clicks shorter than ms.
onHold?: (event: React.MouseEvent, target: EventTarget) => void, // ...for clicks longer than ms.
onRelease?: () => void, // Fired just after onHold.
ms: number, // The measurement of longness for clicking and holding.
}
```## Inspiration
Inspired by (and highly recommended reading): https://spacejelly.dev/posts/how-to-detect-long-press-gestures-in-javascript-events-in-react (Author: Colby Fayock, thanks.)