Docs
Long Press

Long Press

Enable precise control of long-press interactions for both touch and mouse events

About

The useLongPress hook enhances React applications by managing long-press interactions for both mouse and touch events, ensuring a consistent user experience across devices. This hook allows for customization, providing developers the flexibility to adjust the long-press functionality according to their application needs.

Parameters

NameTypeDescription
callbackfunctionThis is the function to be executed when a long press event is detected.
optionsobjectThis is an optional configuration object provided when calling useLongPress.
options.thresholdnumberThis is the time (in milliseconds) the user must press and hold to trigger a long press event. Default value is 400.
options.onStartfunctionThis function is called when the user starts pressing.
options.onFinishfunctionThis function is called when a long press event finishes successfully (the user releases after the threshold).
options.onCancelfunctionThis function is called when a press event is cancelled (the user releases before the threshold).

Return Values

NameTypeDescription
onMouseDownfunctionThis is the mouse down event handler.
onMouseUpfunctionThis is the mouse up event handler.
onMouseLeavefunctionThis is the mouse leave event handler.
onTouchStartfunctionThis is the touch start event handler.
onTouchEndfunctionThis is the touch end event handler.

Installation

Run the following command:

npx scriptkavi-hooks@latest add long-press

Usage

import { useLongPress } from "@/hooks/long-press"
import * as React from "react"
 
import { closeIcon } from "./icons"
 
export default function App() {
  const [isOpen, setIsOpen] = React.useState(false)
  const attrs = useLongPress(
    () => {
      setIsOpen(true)
    },
    {
      onStart: (event) => console.log("Press started"),
      onFinish: (event) => console.log("Press Finished"),
      onCancel: (event) => console.log("Press cancelled"),
      threshold: 500,
    }
  )
 
  return (
    <section>
      <h1>useLongPress</h1>
      <button {...attrs} className="primary">
        Press Me
      </button>
      {isOpen && (
        <dialog>
          <button onClick={() => setIsOpen(false)}>{closeIcon}</button>
          <h2>Modal</h2>
          <p>This is a modal triggered by a long press.</p>
        </dialog>
      )}
    </section>
  )
}