Docs
useKeyPress
Detect and perform actions on key press events with useKeyPress.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-key-press
Usage
"use client"
import * as React from "react"
import { useKeyPress } from "@/hooks/use-key-press"
export function Component() {
const [activeKey, setActiveKey] = React.useState<string>("")
const handleKeyPress = React.useCallback((e: KeyboardEvent) => {
e.preventDefault()
setActiveKey(e.key)
setTimeout(() => setActiveKey(""), 600)
}, [])
useKeyPress({
keyPressItems: [
{
keys: ["UpArrow"],
event: handleKeyPress,
},
{
keys: ["DownArrow"],
event: handleKeyPress,
},
{
keys: ["LeftArrow"],
event: handleKeyPress,
},
{
keys: ["RightArrow"],
event: handleKeyPress,
},
],
})
return (
<section>
<p>Press any arrow key on your keyboard</p>
<div className="button-grid">
<button className={activeKey === "ArrowUp" ? "active" : ""}>↑</button>
<button className={activeKey === "ArrowLeft" ? "active" : ""}>←</button>
<button className={activeKey === "ArrowDown" ? "active" : ""}>↓</button>
<button className={activeKey === "ArrowRight" ? "active" : ""}>
→
</button>
</div>
{activeKey && <p>{activeKey} pressed!</p>}
</section>
)
}
API Reference
Parameter
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
useKeyPress Options | ||||
keyPressItems | KeyPressItem[] | Array of key press combinations and their associated events to monitor. | Required | No |
tagsToIgnore | string[] | Array of HTML tag names where key events should not trigger (e.g., input fields). | ["INPUT", "TEXTAREA", "SELECT"] | Yes |
triggerOnContentEditable? | boolean | Whether to trigger events on elements with contenteditable="true" . | false | Yes |
KeyPressItem Interface | ||||
keys | Array<keyof typeof Keys> | Array of key codes (from the Keys object) that must be pressed to trigger the event. | Required | No |
event | (event: KeyboardEvent) => void | Function to call when the key combination is pressed. | Required | No |
preventDefault | boolean | Whether to call event.preventDefault() when the key combination is detected. | true | Yes |