Skip to main content

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.

If you want to invoke a callback for all KeyboardEvent.key values, use the allKeyDownCallback option.

  • 💡 When allKeyDownCallback is set, callbacks defined in keyDownCallbackMap are 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

🔗 View source code


Interface

typescript
interface UseKeyDownProps {
enabled?: boolean;
keyDownCallbackMap?: Partial<KeyDownCallbackMap>;
allKeyDownCallback?: (event: KeyboardEvent) => void;
}
typescript
// 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

NameTypeDefaultDescription
enabledbooleantrueWhether to activate the keyboard event listener
keyDownCallbackMapPartial<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

NameTypeDescription
refReact.RefObject<T | null>Ref to attach to the target element for key binding. Binds to window if not assigned

Remarks

keyDownCallbackMap type inference

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.

typescript
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.

typescript
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' }}
/>
);
};

Example


Remarks