react-keybinder
Version:
🚀 A simple React hook for handling keyboard shortcuts and keybindings effortlessly.
44 lines (43 loc) • 1.7 kB
JavaScript
import { useEffect } from "react";
var useKeyBinder = function (keyCombo, callback) {
useEffect(function () {
var handleKeydown = function (event) {
var keys = keyCombo
.toLowerCase()
.split("+")
.map(function (key) { return key.trim(); });
// Modifier keys
var ctrl = keys.includes("ctrl") || keys.includes("control");
var shift = keys.includes("shift");
var alt = keys.includes("alt");
var meta = keys.includes("meta") ||
keys.includes("cmd") ||
keys.includes("command");
// The actual key
var mainKey = keys.find(function (key) {
return ![
"ctrl",
"control",
"shift",
"alt",
"meta",
"cmd",
"command",
].includes(key);
});
// Check if all modifier keys match
var isMatch = (ctrl ? event.ctrlKey : true) &&
(shift ? event.shiftKey : true) &&
(alt ? event.altKey : true) &&
(meta ? event.metaKey : true) &&
(mainKey ? event.key.toLowerCase() === mainKey : true);
if (isMatch) {
event.preventDefault(); // Optional: Prevent default browser action
callback(event);
}
};
window.addEventListener("keydown", handleKeydown);
return function () { return window.removeEventListener("keydown", handleKeydown); };
}, [keyCombo, callback]);
};
export { useKeyBinder };