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

NameTypeDescriptionDefault ValueOptional
useKeyPress Options
keyPressItemsKeyPressItem[]Array of key press combinations and their associated events to monitor.RequiredNo
tagsToIgnorestring[]Array of HTML tag names where key events should not trigger (e.g., input fields).["INPUT", "TEXTAREA", "SELECT"]Yes
triggerOnContentEditable?booleanWhether to trigger events on elements with contenteditable="true".falseYes
KeyPressItem Interface
keysArray<keyof typeof Keys>Array of key codes (from the Keys object) that must be pressed to trigger the event.RequiredNo
event(event: KeyboardEvent) => voidFunction to call when the key combination is pressed.RequiredNo
preventDefaultbooleanWhether to call event.preventDefault() when the key combination is detected.trueYes