Sure, itâs a tricky one! Iâm using this debugging as practice for myself, so my solution may not be the most efficient.
The ref doesnâ serve any purpose here I donât think.
It could be simpler to use the playSound
method to see if a key was pressed, or if the button was clicked. It will also help you keep your code DRY.
By having one playSound
method, you could assign the audio element like so:
// note that we removed the ref binding, and the keypress binding and function
// also removed the id and ref from the audio file.
playSound=(e)=>{
this.setState({
play:!this.state.play,
});
// this is checking if `e.key` exists. If it does (truthy) then it assigns
// the element variable otherwise it's undefined
const element = e.key && document.getElementById(e.key.toUpperCase())
// the below checks if element has been assigned in the line above.
// If it has, then the querySelector is assigned from the element variable, if not, then it means it's been clciked, and get's it from the `e.target`
const audio = element ? element.querySelector('audio') : e.target.querySelector('audio')
audio.play();
audio.currentTime = 0;
}
You should also not have any DOM elements with the same id
, this is often a cause of bugs, and is considered bad practice.
This getâs it working, but may not be clear why or how, so please ask more questions! 