Skip to content

useKeyPress ​

Hook that listens for key press events

sensors
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { useKeyPress } from '@siberiacancode/reactuse';

Usage ​

typescript
const isKeyPressed = useKeyPress('a', window);
// or
const { pressed, ref } = useKeyPress('a');

Demo ​

Api ​

Parameters

NameTypeDefaultNote
target?HookTargetwindowThe target to attach the event listeners to
keyUseKeyPressKey-The key or keys to listen for
callback?(pressed: boolean, event: KeyboardEvent) => void-Callback function invoked when key is pressed

Returns

boolean

Parameters

NameTypeDefaultNote
keyUseKeyPressKey-The key or keys to listen for
callback?(pressed: boolean, event: KeyboardEvent) => void-Callback function invoked when key is pressed

Returns

{ pressed: boolean; ref: StateRef<Target> }

Type declaration ​

typescript
import type { HookTarget } from '@/utils/helpers';

import type { StateRef } from '../useRefState/useRefState';

export type UseKeyPressKey = string | string[];

export type UseKeyPressCallback = (pressed: boolean, event: KeyboardEvent) => void;

export interface UseKeyPress {
  (target: HookTarget | Window, key: UseKeyPressKey, callback?: UseKeyPressCallback): boolean;

  <Target extends Element>(
    key: UseKeyPressKey,
    callback?: UseKeyPressCallback,
    target?: never
  ): { pressed: boolean; ref: StateRef<Target> };
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
H
hywax
hywax
G
Gorilla Dev
Gorilla Dev

Released under the MIT License.