Drum Machine with hooks question

Hello, I tried completing the Drum machine project but this time with hooks as that is something I am trying to learn.
I think I made a decent app here, only problem there is that when you press a key(Q,W,E…etc) AND the power is turned ‘off’, the drum still plays which shouldn’t be the case and I can’t figure out how to do it.
Anyone with some advice on this?
Thanks in advance.

Hey there,

great work so far!

As you can see, your event runs two times. In general it’s not good practice to use the native event listeners like you do.

React can handle this for you, because it has an event for pressing a key. You can add the listener to a div and use the React synthetic event for this.

1 Like

In all honesty, I didn’t get 75% of your answer after reading it the first time, but after reading the react website I can see now you gave me some excellent advice on how to handle events in React, so thank you very much for that.

However, now my code works even less than before.
I removed the useEffect and window.addEventListener, replaced it with a “onKeyPress” on the outer div with a method, even added a “tabIndex=0” to put focus on the div, and now nothing happens when I press a key.
Reworked project here

Your code is working fine for me.

When I open the page and press one of the buttons nothing happens, only when I click inside the orange box, this works. So it somehow works but not entirely.

Alright, so your listener is registered to the outer div. My best idea is to create a container that takes the whole window size around your current div and set it to focus on loading.

1 Like