useKeyPress
Tracks whether specific keys are pressed.
Usage
import { useKeyPress } from "@siberiacancode/reactuse";
const keyPress = useKeyPress<HTMLDivElement>("a");
// or
const keyPress = useKeyPress(ref, "a");Example
import { useKeyPress } from "@siberiacancode/reactuse";
export const Spacebar = () => {
const keyPress = useKeyPress<HTMLDivElement>("a");
return (
<div ref={keyPress.ref}>{keyPress.pressed ? "Pressed" : "Released"}</div>
);
};key as array (match any):
const keyPress = useKeyPress<HTMLDivElement>(["ArrowLeft", "ArrowRight"]);callback:
const keyPress = useKeyPress<HTMLDivElement>("Escape", (pressed, event) => {
console.log(pressed, event.key);
});Type Declarations
import type { HookTarget } from "@siberiacancode/reactuse";
import type { StateRef } from "@siberiacancode/reactuse";
export type UseKeyPressKey = string | string[];
export type UseKeyPressCallback = (
pressed: boolean,
event: KeyboardEvent
) => void;
export interface UseKeyPressReturn {
pressed: boolean;
ref: StateRef<Element>;
}
export interface UseKeyPress {
(
target: HookTarget | Window,
key: UseKeyPressKey,
callback?: UseKeyPressCallback
): UseKeyPressReturn;
<Target extends Element>(
key: UseKeyPressKey,
callback?: UseKeyPressCallback,
target?: never
): UseKeyPressReturn & { ref: StateRef<Target> };
}
export declare const useKeyPress: UseKeyPress;