key-event-utils
v1.0.3
Published
KeyBoard Key Event Utils
Maintainers
Readme
KeyboardEventUtils is a utility module for handling keyboard events in React applications. It provides helper functions to check for specific key presses, optionally with modifier keys (e.g., Ctrl, Alt, Shift, Meta) and by default strict check for the key.
Features
- Detects specific key presses such as
Enter,Tab,Escape, arrow keys, and more. - Supports checking for modifier keys (
Ctrl,Alt,Shift,Meta/Cmd). - Simplifies keyboard event handling in React components.
Installing
npm i key-event-utilsImporting the Utility
import {KeyboardEventUtils} from 'key-event-utils';Usage
Each key has a corresponding function to check if it was pressed. For example:
function handleKeyDown(event: React.KeyboardEvent) {
if (KeyboardEventUtils.isEnterKey(event)) {
console.log("Enter key pressed! No modifiers Pressed");
}
if (KeyboardEventUtils.isEnterKey(event,"*")) {
console.log("Enter key pressed!"); // Any modifiers is allowed
}
if (KeyboardEventUtils.isEscapeKey(event, "ctrl")) {
console.log("Escape key pressed with Ctrl!");
}
}You can specify modifiers as a string; Case doesn’t matter ctrl, Ctrl or CTRL will work. Supported modifiers are:
ctrlaltshiftmetaorcmd, mentioning one modifier itself will work, no need for OS specific.
Keys Supported
The following keys are supported and its corresponding methods:
Enter-isEnterKeyTab-isTabKeyEscape-isEscapeKeyBackspace-isBackspaceKeyDelete-isDeleteKey- Arrow keys:
ArrowUp,ArrowDown,ArrowLeft,ArrowRight-isUpArrowKey... got the pattern right?
