Guess who's back, it's me!
I really enjoyed making my first youtube video, so I decided to start a series on creating custom react hooks!
This one's about creating a useKey
hook, that allows you to know when a certain keyboard key is pressed. I also cover some of the "rules of hooks", how short circuit evaluation violates the rules, and how to get around that..
Again, any feedback is highly appreciated, thanks for reading and/or watching!
function useKey(key) {
// Keep track of key state
const [pressed, setPressed] = useState(false)
// Does an event match the key we're watching?
const match = event => key.toLowerCase() == event.key.toLowerCase()
// Event handlers
const onDown = event => {
if (match(event)) setPressed(true)
}
const onUp = event => {
if (match(event)) setPressed(false)
}
// Bind and unbind events
useEffect(() => {
window.addEventListener("keydown", onDown)
window.addEventListener("keyup", onUp)
return () => {
window.removeEventListener("keydown", onDown)
window.removeEventListener("keyup", onUp)
}
}, [key])
return pressed
}
Top comments (3)
I am just learning to code, but I got this to work with the space bar:
// Event handlers
const onDown = event => {
if (match(event)) {
setPressed(true)
}
if (event.code === 'Space' && key === 'Space') {
console.log('Space pressed');
setPressed(true);
}
I found this very useful by the way.
hey, do you know how to access the spacebar with this?