useKeyPress

Detect and perform actions on key press events with useKeyPress.

Install:

Note: This hook depends on React’s experimental useEffectEvent.

npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental

Description:

The useKeyPress hook is a useful for detecting key presses and performing specific actions based on the pressed key. By calling useKeyPress with the desired key and callback function, the hook sets up an event listener that triggers the callback when the specified key is pressed.

Parameters

NameTypeDescription
keystringThe key to listen for.
cbfunctionThe callback function to be executed when the key is pressed.
optionsobject(Optional) Additional options for the key press event.
options.eventstring(Optional) The event type to listen for. Default is "keydown".
options.targetDOM element or window(Optional) The target element or window object to attach the event listener to. Default is window.
options.eventOptionsobject(Optional) Additional options for the event listener.

Demo:

Example:

More Hooks:

Sort: