Issues with key events (not working)

I’m not sure where the disconnect is happening, but this was playing the sound before I lifted the state. Also, is there a way to set off my handleChange if the keyCode exists in my keys? That way, I wouldn’t have to worry about how to update the state for the new keyName. If there is a better way of doing this please let me know. Here is my code.

You do not have this.props.keys in the parent component.

You can use the same technique for the keypress as you do with the mouse click, event.key will be the letter of the key pressed, you can use that to get to the auto element by its id (letter needs to be uppercase) and then call .play() on the element.

But grab the audio element first and check that it is in fact the element (i.e. a key was pressed that corresponds to an audio element id) before calling .play() on it. You can do this by checking the value you get back from getElementById is truthy.

element &&

Hey, thanks for saving the day again! I’m not sure if I’m doing this quite right. It seems to work, but I don’t fully understand what this does exactly. Take a look.

audioElement &&

 handleKeyPress(event) {
    const keyPressed = event.key.toUpperCase(); {
    const audioElement = document.getElementById(keyPressed)    
    audioElement &&

Yep, that looks right.

You mean this code?
audioElement &&

getElementById will return null if it fails to find an element with the id provided to it and null is a falsy value. Read the MDN docs on the && operator and see if you can make sense of why the code does what it does.

1 Like

Thanks, I’m gonna give it a read.

Okay, I do understand what is happening there now.