Keyboard key handler hook for react
npm install @rooks/use-key```
npm install rooks
or
``
yarn add rooks
Rooks is completely treeshakeable and if you use only 1 of the 50+ hooks in the package, only that hook will be bundled with your code. Your bundle will only contain the hooks that you need. Cheers!
!Build Status   
``
npm install --save @rooks/use-key
`javascript`
import useKey from "@rooks/use-key";
#### Basic example with keydown
` Press enter anywhere to trigger a console.log statement Press a,e,i,o,u in the input to trigger a console.log statement Press A,E,I,O,U in the input to trigger a different log statementjsx
function Demo() {
const inputRef = useRef();
function windowEnter(e) {
console.log("[Demo 1] Enter key was pressed on window");
}
function vowelsEntered(e) {
console.log("[Demo 1] You typed a vowel");
}
function capitalVowelsEntered(e) {
console.log("[Demo 1] You typed a capital vowel");
}
// window is the target
useKey(["Enter"], windowEnter);
useKey(["a", "e", "i", "o", "u"], vowelsEntered, {
target: inputRef
});
useKey(["A", "E", "I", "O", "U"], capitalVowelsEntered, {
target: inputRef
});
return (
<>
>
);
}
render(
`
#### Multiple kinds of events
`jsx
function Demo() {
const inputRef = useRef();
function onKeyInteraction(e) {
console.log("[Demo 2]Enter key", e.type);
}
useKey(["Enter"], onKeyInteraction, {
target: inputRef,
eventTypes: ["keypress", "keydown", "keyup"]
});
return (
<>
Try "Enter" Keypress keydown and keyup
It will log 3 events on this input. Since you can listen to multiple
types of events on a keyboard key.
#### Conditionally setting handlers
`jsx
function Demo() {
const inputRef = useRef();
const [shouldListen, setShouldListen] = useState(false);
function toggleShouldListen() {
setShouldListen(!shouldListen);
}
function onKeyInteraction(e) {
console.log("[Demo 3] Enter key", e.type);
} useKey(["Enter"], onKeyInteraction, {
target: inputRef,
eventTypes: ["keypress", "keydown", "keyup"],
when: shouldListen
});
return (
<>
Enter key events will only be logged when the listening state is true.
Click on the button to toggle between listening and not listening
states.{" "}
Handy for adding and removing event handlers only when certain
conditions are met.
>
);
}
render( );
``