useKeyPressed
Detect whether keys are currently held down. In a non-browser environment, it always returns false.
API
function useKeyPressed(
keys: string | string[],
options?: {
enabled?: boolean;
target?: EventTarget | React.RefObject<EventTarget | null>;
eventField?: "key" | "code";
},
): boolean;
Parameters:
keys: A key token such as"shift","space"or"a", or an array of tokens where any of them being held down reportstrue. A token is aKeyboardEvent.keyvalue (or aKeyboardEvent.codename whenoptions.eventFieldis"code") and is case-insensitive; the aliasesesc,space,plus,up,down,leftandrightare also accepted.options: Options object.options.enabled: Whether to track the keys. Default istrue.options.target: The event target that receives thekeydownlistener: an element,window,document, or a ref of them. Default isdocument.options.eventField: TheKeyboardEventfield the key token is compared against:"key"(the produced character) or"code"(the physical key position). Default is"key".
Results:
- Returns
trueif any of the keys is held down, otherwisefalse.
Notes
- Modifiers are not part of the key token: pressing
kwith any modifier held down still reports"k"as pressed. Modifier keys themselves are ordinary keys ("control","shift","alt","meta");modis not supported, useuseHotkeyfor shortcuts. - Releases are tracked on the document, so a key released after the focus left
targetis still reported as released. - The state is reset when the window loses focus or the page becomes hidden, because no
keyupis delivered then. A repeatable key that is still held down reportstrueagain on its next auto-repeat event; keys without auto-repeat, such as"shift", stayfalseuntil they are pressed again. - Unlike
useHotkey, typing in an editable element is not filtered. - Keystrokes produced during an IME composition are ignored.
- With
eventField: "key", akeyupmay report a different key when a modifier or the layout changed while the key was held (for exampleOption+Con macOS); useeventField: "code"for layout-independent input. - With
eventField: "code", tokens are compared withKeyboardEvent.code, so logical names that differ from the physical name never match: use the physical names instead, such as"equal"or"shiftleft". - A key that is already held down when the hook starts tracking reports
falseuntil its next event.
Example
The following example highlights the box while Shift is held down.
Hold Shift
import { useKeyPressed } from "@lilib/hooks";
function Example() {
const shiftPressed = useKeyPressed("shift");
return (
<div
style={{
padding: 8,
borderRadius: 4,
transition: "all 150ms",
transform: shiftPressed ? "scale(1.1)" : "none",
backgroundColor: shiftPressed ? "#d4edda" : "#f8f9fa",
}}
>
{shiftPressed ? "Shift is held down" : "Hold Shift"}
</div>
);
}
export default Example;