shadcn-ahooks

useKeyPress

Listen for the keyboard press, support key combinations, and support alias.

Overview

Listen for the keyboard press, support key combinations, and support alias.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useKeyPress.json

Listen 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

  1. All key alias refer to code

  2. Modifier keys

ctrl
alt
shift
meta

On this page