useKeyPress
Runs a handler when matching keys are pressed.
Runs a handler when matching keys are pressed.
Import
import { useKeyPress } from '@kamod-ch/hooks'Live demo
Basic demo
Runs a handler when matching keys are pressed.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useKeyPress } from '@kamod-ch/hooks'
export default function UseKeyPressDemo() {
const ref = useRef<HTMLDivElement>(null)
const [count, setCount] = useState(0)
const [last, setLast] = useState('none')
useKeyPress('k', (event, key) => {
setCount((value) => value + 1)
setLast(String(key || event.key))
}, { target: ref })
return (
<div>
<div ref={ref} class="demo-target-box" tabIndex={0}>Focus here and press the “k” key.</div>
<p><strong>Last key:</strong> {last}</p>
<p><strong>Recognized presses:</strong> {count}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
export type KeyType = number | string;
export type KeyPredicate = (event: KeyboardEvent) => KeyType | boolean | undefined;
export type KeyFilter = KeyType | KeyType[] | ((event: KeyboardEvent) => boolean);
export type KeyEvent = 'keydown' | 'keyup';
export type Target = BasicTarget<HTMLElement | Document | Window>;
export type Options = {
events?: KeyEvent[];
target?: Target;
exactMatch?: boolean;
useCapture?: boolean;
};
declare function useKeyPress(keyFilter: KeyFilter, eventHandler: (event: KeyboardEvent, key: KeyType) => void, option?: Options): void;
export default useKeyPress;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.