useKeyboardEvent
hookas/use-keyboard-eventFreeHook
A hook to handle keyboard events
Install it
npx shadcn@latest add https://hookas.letstri.dev/r/use-keyboard-event.jsonSource
1'use client'23import * as React from 'react'45export type KeyboardEventFilter = string | ((event: KeyboardEvent) => boolean)67export function useKeyboardEvent(8 predicate: KeyboardEventFilter,9 callback: (event: KeyboardEvent) => void,10 options: {11 event?: 'keydown' | 'keypress' | 'keyup'12 target?: HTMLElement | React.RefObject<HTMLElement | null>13 deps?: React.DependencyList14 } = {},15): void {16 const { event = 'keydown', target = window } = options17 const callbackEvent = React.useEffectEvent(callback)18 const getPredicateEvent = React.useEffectEvent((ev: KeyboardEvent) => {19 return typeof predicate === 'string'20 ? ev.key === predicate21 : predicate(ev)22 })2324 React.useEffect(() => {25 const abortController = new AbortController()2627 const t = 'current' in target ? target.current : target2829 if (!t) {30 return31 }3233 t.addEventListener(event, (e) => {34 const event = e as KeyboardEvent35 const matches = getPredicateEvent(event)3637 if (matches) {38 callbackEvent(event)39 }40 }, {41 signal: abortController.signal,42 })4344 return () => {45 abortController.abort()46 }47 // eslint-disable-next-line react-hooks/exhaustive-deps48 }, [event, target, ...(options.deps || [])])49}
Files it writes
More from hookas
All 30 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAsyncEffectuse-async-effect | hookas | Hooks | Free | no deps | |
| useClickOutsideuse-click-outside | hookas | Hooks | Free | no deps | |
| useDebounceCallbackuse-debounced-callback | hookas | Hooks | Free | no deps | |
| useDebounceMemouse-debounced-memo | hookas | Hooks | Free | no deps | |
| useDebounceStateuse-debounced-state | hookas | Hooks | Free | no deps | |
| useElementSizeuse-element-size | hookas | Hooks | Free | no deps | |
| useFullscreenuse-fullscreen | hookas | Hooks | Free | no deps | |
| useIntervaluse-interval | hookas | Hooks | Free | no deps |
