useKeyDown
When the element with the assigned ref is focused and a keydown event occurs, the hook triggers the callback mapped to that key in keyDownCallbackMap.
The keys in keyDownCallbackMap must be values returned by KeyboardEvent.key.
- 💡 Commonly used
KeyboardEvent.keyvalues based on Key values for keyboard events - MDN support type inference. Keys not covered by type inference must be entered manually. - 💡 KeyDownCallbackMap interface provided for type inference
If you want to invoke a callback for all KeyboardEvent.key values, use the allKeyDownCallback option.
- 💡 When
allKeyDownCallbackis set, callbacks defined inkeyDownCallbackMapare ignored.
The enabled option lets you conditionally bind the keydown event.
If targetRef is not assigned, the event is bound to window by default.
Code
Interface
interface UseKeyDownProps {
enabled?: boolean;
keyDownCallbackMap?: Partial<KeyDownCallbackMap>;
allKeyDownCallback?: (event: KeyboardEvent) => void;
}
// Function overloading
function useKeyDown({
enabled,
keyDownCallbackMap,
allKeyDownCallback,
}: UseKeyDownProps): { ref: React.RefObject<Window | null> };
function useKeyDown<T extends HTMLElement>({
enabled,
keyDownCallbackMap,
allKeyDownCallback,
}: UseKeyDownProps): { ref: React.RefObject<T | null> };
Options
| Name | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Whether to activate the keyboard event listener |
keyDownCallbackMap | Partial<KeyDownCallbackMap> | {} | An object mapping specific keys to their respective callback functions |
allKeyDownCallback | (event: KeyboardEvent) => void | - | A common callback invoked for every key press. When set, takes priority over keyDownCallbackMap |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<T | null> | Ref to attach to the target element for key binding. Binds to window if not assigned |
Remarks
Type inference is supported for commonly used KeyboardEvent.key values. Keys not covered must be entered as plain strings. See the KeyDownCallbackMap interface for the full list.
Usage
AllKeyDownCallback
A common callback invoked whenever any key is pressed.
import { useKeyDown } from '@modern-kit/react';
const Example = () => {
const { ref } = useKeyDown<HTMLButtonElement>({
enabled: true, // default: true
allKeyDownCallback: (event) => console.log('All Key', event.key)
});
return <button ref={ref}>Button</button>;
};
KeyDownCallbackMap
Maps specific keys to callback functions and invokes the corresponding callback when each key is pressed.
import { useKeyDown } from '@modern-kit/react';
const Example = () => {
const { ref } = useKeyDown<HTMLButtonElement>({
enabled: true, // default: true
keyDownCallbackMap: {
Enter: (event) => console.log('Enter', event.key),
Shift: (event) => console.log('Shift', event.key),
' ': (event) => console.log('Space', event.key),
}
});
return (
<input
ref={ref}
placeholder="Focus here and press Enter, Shift, or Space"
style={{ width: '300px' }}
/>
);
};