Created
February 27, 2021 17:31
-
-
Save christiangenco/5f80c91f56f3945dd9c288d4bf6a2e98 to your computer and use it in GitHub Desktop.
React hook for mousetrap
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 React from "react"; | |
import useMousetrap from "./hooks/useMousetrap"; | |
export default function Example(){ | |
useMousetrap({ | |
a: () => console.log("you pressed a"), | |
"ctrl+space": () => console.log("you pressed ctrl+space"); | |
}); | |
return "lol hi"; | |
} |
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 { useEffect } from "react"; | |
import Mousetrap from "mousetrap"; | |
export default function useMousetrap(keybindings) { | |
useEffect(() => { | |
Object.entries(keybindings).forEach(([key, fn]) => | |
Mousetrap.bind(`${key}`, e => { | |
e.preventDefault(); | |
return fn(e); | |
}) | |
); | |
return () => Object.keys(keybindings).forEach(key => Mousetrap.unbind(key)); | |
}, [keybindings]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment