useKeyPress
Listen for the keyboard press, support key combinations, and support alias.
Overview
Listen for the keyboard press, support key combinations, and support alias.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.jsonListen for the keyboard press, support key combinations, and support alias.
Examples
Basic usage
Combination keys
Exact match
Multiple keys
Get the trigger key
Custom method
Custom DOM
API
type KeyType = number | string;
type KeyFilter = KeyType | KeyType[] | ((event: KeyboardEvent) => boolean);
useKeyPress(
keyFilter: KeyFilter,
eventHandler: (event: KeyboardEvent, key: KeyType) => void,
options?: Options
);Params
| Property | Description | Type | Default |
| | | - |
| keyFilter | Support keyCode、alias、combination keys、array、custom function | KeyType | KeyType[] | (event: KeyboardEvent) => boolean | - |
| eventHandler | Callback function | (event: KeyboardEvent, key: KeyType) => void | - |
| options | Advanced options | Options | - |
Options
| Property | Description | Type | Default |
| - | ---- |
| events | Trigger Events | ('keydown' \| 'keyup')[] | ['keydown'] |
| target | DOM element or ref | () => Element | Element | MutableRefObject<Element> | - |
| exactMatch | Exact match. If set true, the event will only be trigger when the keys match exactly. For example, pressing [shift + c] will not trigger [c] | boolean | false |
| useCapture | to block events bubbling | boolean | false |
Remarks
-
All key alias refer to code
-
Modifier keys
ctrl
alt
shift
meta