-
Notifications
You must be signed in to change notification settings - Fork 0
/
useKeyPressed.js
38 lines (30 loc) · 883 Bytes
/
useKeyPressed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useEffect } from "react";
// Usage
function App() {
useKeyPresses("esc", () => {
// your code here...
});
return (
<div>...</div>
);
}
// Hook
const keyNameNumberMap = {
"esc": 27,
};
function useKeyPresses(keyName, callback) {
useEffect(() => {
const handleKeyDown = (event) => {
const keyNumber = keyNameNumberMap[keyName];
if (!keyNumber) {
throw new Error(`Key name "${keyName}" does not exist! You can add it inside a useKeyPress hook.`);
}
if (event.keyCode === keyNumber && typeof callback === "function") {
callback();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [keyName, callback]);
}
export default useKeyPresses;