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

PropertyDescriptionTypeDefault
keyFilterSupport keyCode、alias、combination keys、array、custom functionKeyType | KeyType[] | (event: KeyboardEvent) => boolean-
eventHandlerCallback function(event: KeyboardEvent, key: KeyType) => void-
optionsAdvanced optionsOptions-

Options

PropertyDescriptionTypeDefault
eventsTrigger Events('keydown' | 'keyup')[]['keydown']
targetDOM element or ref() => Element | Element | MutableRefObject<Element>-
exactMatchExact match. If set true, the event will only be trigger when the keys match exactly. For example, pressing [shift + c] will not trigger [c]booleanfalse
useCaptureto block events bubblingbooleanfalse

Remarks

  1. All key alias refer to code

  2. Modifier keys

ctrl
alt
shift
meta

On this page