useKeyboard ​
Hook that helps to listen for keyboard events
sensors
test coverage
Last changed: 14 days ago
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
Name | Type | Default | Note |
---|---|---|---|
target | HookTarget | - | The target to attach the event listeners to |
callback | KeyboardEventHandler | - | The callback function to be invoked on key down |
Returns
void
Parameters
Name | Type | Default | Note |
---|---|---|---|
target | HookTarget | - | The target to attach the event listeners to |
options? | UseKeyboardEventOptions | - | The keyboard event options |
Returns
void
Parameters
Name | Type | Default | Note |
---|---|---|---|
callback | KeyboardEventHandler | - | The callback function to be invoked on key down |
Returns
{ ref: StateRef<Target> }
Parameters
Name | Type | Default | Note |
---|---|---|---|
options? | UseKeyboardEventOptions | - | The keyboard event options |
Returns
{ ref: StateRef<Target> }
Type declaration ​
typescript
import type { HookTarget } from '@/utils/helpers';
import type { StateRef } from '../useRefState/useRefState';
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
): { ref: StateRef<Target> };
<Target extends HTMLElement>(
options: UseKeyboardEventOptions,
target?: never
): {
ref: StateRef<Target>;
};
}
Source ​
Source • DemoContributors ​
D