Skip to content

useHotkeys

Hook that listens for hotkeys

sensors
medium
test coverage
Last changed: 11 days ago

Installation

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

Usage

typescript
useHotkeys(ref, 'ctrl+a', { onChange: () => console.log('hotkey pressed') });
// or
useHotkeys(ref, 'ctrl+a', () => console.log('hotkey pressed'));
// or
const ref = useHotkeys('ctrl+a', { onChange: () => console.log('hotkey pressed') });
// or
const ref = useHotkeys('ctrl+a', () => console.log('hotkey pressed'));

Demo

Api

Parameters

NameTypeDefaultNote
target?HookTargetwindowThe target element to attach the event listener to
hotkeysstring-The hotkey to listen for
options?UseHotkeysOptions-The options for the hook

Returns

void

Parameters

NameTypeDefaultNote
target?HookTargetwindowThe target element to attach the event listener to
hotkeysstring-The hotkey to listen for
callback(event: KeyboardEvent) => void-The callback function to execute when hotkey is pressed
options.alias?Record<string, string>-Alias map for hotkeys
options.enabled?booleantrueEnable or disable the event listeners

Returns

void

Parameters

NameTypeDefaultNote
hotkeysstring-The hotkey to listen for
options?UseHotkeysOptions-The options for the hook

Returns

StateRef<Target>

Parameters

NameTypeDefaultNote
hotkeysstring-The hotkey to listen for
callback(event: KeyboardEvent) => void-The callback function to execute when hotkey is pressed
options.alias?Record<string, string>-Alias map for hotkeys
options.enabled?booleantrueEnable or disable the event listeners

Returns

StateRef<Target>

Type declaration

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

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

export interface UseHotkeysOptions {
  /** Alias map for hotkeys */
  alias?: Record<string, string>;
  /** Enable or disable the event listeners */
  enabled?: boolean;
  /** The callback function to execute when hotkey is pressed */
  onChange?: (event: KeyboardEvent) => void;
}

export type UseHotkeysHotkeys = string;

export interface UseHotkeysKey {
  /** The alias for the key */
  alias: string;
  /** The key code */
  code: string;
  /** The key value */
  key: string;
}

export interface UseHotkeys {
  (target: HookTarget, hotkeys: UseHotkeysHotkeys, options?: UseHotkeysOptions): void;

  (
    target: HookTarget,
    hotkeys: UseHotkeysHotkeys,
    callback: (event: KeyboardEvent) => void,
    options?: UseHotkeysOptions
  ): void;

  <Target extends Element>(
    hotkeys: UseHotkeysHotkeys,
    options?: UseHotkeysOptions,
    target?: never
  ): StateRef<Target>;

  <Target extends Element>(
    hotkeys: UseHotkeysHotkeys,
    callback: (event: KeyboardEvent) => void,
    options?: UseHotkeysOptions,
    target?: never
  ): StateRef<Target>;
}

Source

SourceDemo

Contributors

D
debabin
debabin
H
hywax
hywax

Released under the MIT License.