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
Name | Type | Default | Note |
---|---|---|---|
target? | HookTarget | window | The target to attach the event listeners to |
key | UseKeyPressKey | - | The key or keys to listen for |
callback? | (pressed: boolean, event: KeyboardEvent) => void | - | Callback function invoked when key is pressed |
Returns
boolean
Parameters
Name | Type | Default | Note |
---|---|---|---|
key | UseKeyPressKey | - | 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 • DemoContributors ​
D
H
G