My component structure is as follows:
<DrumMachine>
<DrumPad>
When I add the keydown listener in the top level component, I am able to return the keycode of the key pressed. However, when I move the same code to the drumpad component, the keydown event fires, however the keycode is always undefined.
Below is the abbreviated code for the DrumPad component
class DrumPad extends React.Component{
constructor(props){
super(props)
this.playSound = this.playSound.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
componentDidMount(){
document.addEventListener("keydown", this.handleKeyDown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyDown);
}
handleKeyDown(e){
console.log("key was pressed: ", e.keyCode)
}
playSound(e){
if (e.target.children[1] && this.props.power){
this.props.drumMachine.setState({display: e.target.id})
let audio = e.target.children[1]
audio.currentTime = 0;
audio.play();
}
}
}
This is how it is called within DrumMachine component
render(){
return (
<div id="drum-machine">
<div id="drum-pad-wrapper">
<div class="drum-pad-group">
{this.props.musicLibs[this.state.musicLib].slice(0,3).map((obj) => {
return <DrumPad music={obj} drumMachine={this} power={this.state.power} />
})}
</div>
//rest of code omitted
To see the full code, you can view my codepen: https://codepen.io/verdi327/full/aPvWKq
Thanks!