Last active
January 30, 2019 08:09
-
-
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 !
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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