Skip to content

Instantly share code, notes, and snippets.

@olup
Last active January 30, 2019 08:09
Show Gist options
  • Save olup/09c8d05d4d0a42b35981b17bca1a10a8 to your computer and use it in GitHub Desktop.
Save olup/09c8d05d4d0a42b35981b17bca1a10a8 to your computer and use it in GitHub Desktop.
A REACT HOOK to declare Mousetrap.js hotkey combo associated to a callback. Two effect hooks are needed as we don't want to bind mousetrap at every keystroke !
// use it like this in your component
mouseTrapHook([
{
keys: "ctrl+enter", // any mousetrap combo, or array of combo
action: () => { // triggered on key combo
// whatever. You can use your state in there too.
}
}
]);
// NOTE : if combo happens in a textarea or input, don't forget to add className="mousetrap" to it - or mousetrap will ignore it.
import mousetrap from "mousetrap";
import react, { useEffect, useState } from "react";
export default handlerMap => {
const [index, setIndex] = useState(-1);
useEffect(() => {
handlerMap.map((handler, index) => {
mousetrap.bind(handler.keys, () => setIndex(index));
});
return () => {
handlerMap.map(handler => {
mousetrap.unbind(handler.keys);
});
};
}, []);
useEffect(
() => {
if (index > -1) {
handlerMap[index].action();
}
return () => {
setIndex(-1);
};
},
[index]
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment