Skip to content

useKeyboard

Hook that helps to listen for keyboard events

sensors
medium
test coverage
Last changed: last month

Installation

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

Usage

typescript
useKeyboard(ref, (event) => console.log('key down'));
// or
useKeyboard(ref, { onKeyDown: (event) => console.log('key down'), onKeyUp: (event) => console.log('key up') });
// or
const ref = useKeyboard((event) => console.log('key down'));
// or
const ref = useKeyboard({ onKeyDown: (event) => console.log('key down'), onKeyUp: (event) => console.log('key up') });

Demo

Api

Parameters

NameTypeDefaultNote
targetHookTarget-The target to attach the event listeners to
callbackKeyboardEventHandler-The callback function to be invoked on key down

Returns

void

Parameters

NameTypeDefaultNote
targetHookTarget-The target to attach the event listeners to
options?UseKeyboardEventOptions-The keyboard event options

Returns

void

Parameters

NameTypeDefaultNote
callbackKeyboardEventHandler-The callback function to be invoked on key down

Returns

StateRef<Target>

Parameters

NameTypeDefaultNote
options?UseKeyboardEventOptions-The keyboard event options

Returns

StateRef<Target>

Type declaration

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

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

export type UseKeyboardReturn<Target extends HTMLElement> = StateRef<Target>;

export type KeyboardEventHandler = (event: KeyboardEvent) => void;

export interface UseKeyboardEventOptions {
  /** The callback function to be invoked on key down */
  onKeyDown?: KeyboardEventHandler;
  /** The callback function to be invoked on key up */
  onKeyUp?: KeyboardEventHandler;
}

export interface UseKeyboard {
  (target: HookTarget, callback: KeyboardEventHandler): void;

  (target: HookTarget, options: UseKeyboardEventOptions): void;

  <Target extends HTMLElement>(callback: KeyboardEventHandler, target?: never): StateRef<Target>;

  <Target extends HTMLElement>(options: UseKeyboardEventOptions, target?: never): StateRef<Target>;
}

Source

SourceDemo

Contributors

D
debabin
debabin
F
forckes
forckes

Released under the MIT License.