usePress Hook
Introduction
A custom React Hook for detecting long-press actions.
Play
Usage
import { useEffect, useRef, useState } from "react";
import { useLongPress } from "@cannonui/reacthooks";
const TestUseLongPress = () => {
const callback = () => {
console.log("long press detected");
};
// Use the setLongPressed function to update the longPressed state
const { longPressed, element } = useLongPress({
threshold: 3000,
callback,
});
return (
<div ref={element}>
<button>Press and hold</button>
<div>{longPressed && <span>long pressed</span>}</div>
</div>
);
};
export default TestUseLongPress;
Return Value
The hook returns an object containing the element reference and the long-press state.
Parameters
Name | Type | Description |
---|---|---|
options | longPressProps | An object containing the necessary information for the long-press action. |
threshold | number | The duration (in milliseconds) required to trigger the long-press action. |
onStart | () => void | A callback function triggered when the long-press action starts. |
onFinish | () => void | A callback function triggered when the long-press action is completed. |
callback | (e: HTMLDivElement) => void | A callback function executed when the long-press action is triggered, with the element reference as a parameter. |
onCancel | () => void | A callback function triggered when the long-press action is canceled. |
Example
In this example, we have a component called TestUseLongPress
that uses the useLongPress
Hook to detect long-press actions. When the user presses and holds the button for a certain duration (6000 milliseconds), the callback
function is triggered, and the longPressed
state is set to true
.
Use Scenario
The useLongPress
Hook is useful in scenarios where you want to detect long-press actions by the user and trigger corresponding callbacks. For example, in some applications, long-press actions might be used to display context menus, activate drag-and-drop functionality, or perform a series of specific tasks. By using the useLongPress
Hook, you can easily implement long-press-related features and provide a better interactive experience for users.