A simple React hook for listening to custom keyboard events. This hook is also SSR safe and does not break when used without window
existing.
Install this package with npm
.
npm i @phntms/use-key
To listen to a single key:
import useKey from "@phntms/use-key";
useKey("Escape", (pressed: boolean) => {
if (pressed) // Do something on "Escape"...
});
To listen to key modifiers:
import useKey from "@phntms/use-key";
useKey("g", (pressed: boolean, event: KeyboardEvent) => {
if (pressed && event.ctrlKey) // Do something on "Ctrl + G"...
});
The hook uses KeyboardEvent under the hood. This means using the onChange
event, you can get the state of modifier keys such as Shift as well as the keyboard locale and layout.
Want to get involved, or found an issue? Please contribute using the GitHub Flow. Create a branch, add commits, and open a Pull Request or submit a new issue.
Please read CONTRIBUTING
for details on our CODE_OF_CONDUCT
, and the process for submitting pull requests to us!