A small React + TypeScript utility to handle keyboard shortcuts in a simple and reusable way.
It provides:
- A
useShortcuthook to handle keyboard shortcuts on any element - A
Shortcutcomponent to wrap elements and enable shortcuts easily
- Node.js 18+
- React 18 or 19 in the consuming project
This package is not published to npm. You can build and install it locally.
Inside the react-shortcut folder:
npm install
If you have a build script configured (for example with tsc):
npm run buildIf you are using the TypeScript source directly, this step may not be necessary.
You can generate a .tgz package using:
npm packThis will generate a file like:
react-shortcut-1.0.0.tgz
Inside your react project:
npm install /path/to/react-shortcut/react-shortcut-1.0.0.tgzOr install directly from the folder:
npm install /path/to/react-shortcutUsing the useShortcut Hook
Attach the returned callback to any focusable element's onKeyDown:
import React, { useCallback } from "react";
import { useShortcut } from "react-shortcut";
function MyComponent() {
const onKey = useCallback((key: string, event: KeyboardEvent) => {
alert(`Handled key: ${key}`);
}, []);
const onKeyDown = useShortcut("x", onKey);
return (
<button onKeyDown={onKeyDown}>
Press "x" while this button is focused
</button>
);
}
You can also pass multiple keys:
useShortcut(["a", "b", "c"], onKey);
Using the Shortcut component
The Shortcut component wraps any element and injects the onKeyDown handler automatically:
import React, { useCallback } from "react";
import { Shortcut } from "react-shortcut";
function MyComponent() {
const onKey = useCallback((key: string, event: KeyboardEvent) => {
alert(`Handled key: ${key}`);
}, []);
return (
<Shortcut keys="x" onKey={onKey}>
<button>
Press "x" while this button is focused
</button>
</Shortcut>
);
}
Shortcuts are case-sensitive:
-
"a" is different from "A"
-
This follows the behavior of
event.keyfrom the browse