Skip to main content

useMousePressed

React Sensor Hook that tracks mouse pressing state.

Triggered by mousedown touchstart on target element and released by mouseup mouseleave touchend touchcancel on window

Usage

Live Editor

function Demo() {
  const [mouse, type] = useMousePressed();

  return (
    <div>
      <p>Pressed: {JSON.stringify(mouse)}</p>
      <p>SourceType: {JSON.stringify(type)}</p>
    </div>
  );
};

Result
Loading...

API

useMousePressed

Returns

readonly [boolean, UseMousePressedSourceType]: A tuple with the following elements:

  • whether the mouse is pressed.
  • the pressed source type

Arguments

ArgumentDescriptionTypeDefaultValue
targetdom elementBasicTarget<Element>-
optionsoptional paramsUseMousePressedOptions | undefined-

UseMousePressedOptions

PropertyDescriptionTypeDefaultValue
touchListen to touchstart touchend eventsbooleantrue
dragListen to dragstart drop and dragend eventsbooleantrue
initialValueInitial valuesboolean | (() => boolean)false

UseMousePressedSourceType

Type

export type UseMousePressedSourceType = 'mouse' | 'touch' | null

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;