useHotkeys ​
Hook that listens for hotkeys
sensors
test coverage
Last changed: last month
Installation ​
Library
CLI
Manual
typescript
import { useHotkeys } from '@siberiacancode/reactuse';
Usage ​
typescript
useHotkeys(ref, 'ctrl+a', () => console.log('hotkey pressed'));
// or
useHotkeys(ref, 'ctrl+a, ctrl+b', () => console.log('hotkey pressed'));
// or
const ref = useHotkeys('ctrl+a', () => console.log('hotkey pressed'));
// or
const ref = useHotkeys('ctrl+a, ctrl+b', () => console.log('hotkey pressed'));
Demo ​
Api ​
Parameters
Name | Type | Default | Note |
---|---|---|---|
target? | HookTarget | window | The target element to attach the event listener to |
hotkeys | string | - | 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? | boolean | true | Enable or disable the event listeners |
Returns
void
Parameters
Name | Type | Default | Note |
---|---|---|---|
hotkeys | string | - | 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? | boolean | true | Enable 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;
}
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 type UseHotkeysTarget = Element | React.RefObject<Element | null | undefined>;
export interface UseHotkeys {
(
target: UseHotkeysTarget,
hotkeys: UseHotkeysHotkeys,
callback: (event: KeyboardEvent) => void,
options?: UseHotkeysOptions
): void;
<Target extends Element>(
hotkeys: UseHotkeysHotkeys,
callback: (event: KeyboardEvent) => void,
options?: UseHotkeysOptions,
target?: never
): StateRef<Target>;
}
Source ​
Source • DemoContributors ​
D
H