Event handler working, prop logging properly, when combined it doesn't work?

Event handler working, prop logging properly, when combined it doesn't work?
0.0 0

#1

Hi everyone! :wave:
I’m making my drum machine, and I have a problem with the event handler. Let me show you my code first and then explain. This is my single pad component:

import React, { Component } from 'react';

class Pad extends Component {
    constructor (props) {
        super(props);
        this.handleKeyDown = this.handleKeyDown.bind(this);
    }

    
     handleKeyDown(event) {
        if (event.key === this.props.letter) {
        console.log('something happened')
        }
      }

      componentDidMount() {
        window.addEventListener("keydown", this.handleKeyDown)
      }

    render (){
        return (
        
        <div className="drum-pad">
        <h1>{this.props.letter}</h1>
        </div>
        
    )
        

    }
        
}

export default Pad;

If I console.log event.key, it properly logs the letter (a string saved in the container component state as value for ‘letter’ in an object, in an array of objects, each with keys ‘name’ and ‘letter’ for now, I just got started).
Also the h1 is displaying the letters as expected, so this.props.letter also works.
So why isn’t ‘something happened’ being logged to my console?
I’m sorry if this is a silly question, or if it’s written in a confusing way! Im very new at React and kinda confused myself.

Thanks a lot in advance!!


#2

Have you tried a console.log at the top of handleKeyDown to see if it’s called?


#3

I did. It is called. I’m losing my mind here lol.


#4

Try console.log(event.key === this.props.letter). Is it true when you press the right key?


#5

no! and if I console.log(event.key, this.props.letter), I get the key I’m pressing and all the letters… I must be calling it on the wrong component ??
EDIT: to clarify, if I console.log(event.key, this.props.letter), I get:
a Q
a W
a E
a A
a S
a D
a Z
a X
a C


#6

Then this.props.letter is the problem. Need the parent component for that.


#7

You mean I need to call handleKeyDown from the parent component?


#8

I might be wrong, but it seems to me that if you’re pressing the letter ‘a’ your this.props.letter changes for some reason. Post the parent component.


#9

It’s the fact that the letter is a string, and it’s capitalized, so it’s only true when its “A”, not “a”. I’m using strings. That’s the problem. I should be using event.which and key codes.