DEV Community

Spacie
Spacie

Posted on

Keyboard input with React Hooks

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
}

Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
bmills23453218 profile image
Benjamin Mills

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);
}

}

const onUp = event => {
    if (match(event)) {
        setPressed(false);
    }
    if (event.code === 'Space' && key === 'Space') {
        console.log('Space released');
        setPressed(false);
      }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bmills23453218 profile image
Benjamin Mills

I found this very useful by the way.

Collapse
 
bmills23453218 profile image
Benjamin Mills

hey, do you know how to access the spacebar with this?