Drum Machine Keydown Event Not Returning Key

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!

I think you need to bind it to this.

document.addEventListener("keydown", this.handleKeyDown.bind(this));

Wow! That solved it. Could you please explain why it worked? I have it bound to this in the constructor, which I thought loaded before the componentDidMount() call. Is the binding to this in the document.addEventListener("keydown", this.handleKeyDown.bind(this)); a different reference?

Thanks!

Sorry, that’s a little beyond my understanding. I think that because you are passing this.handleKeyDown to the document.addEventListener, it needs to know that you want it operating in the this of your component, not the document. But again, this is a little beyond me.