Why does this function need another function?(React/js)

Hello, I have been working on the Drum Machine project, I got something working (thanks to other projects) but there’s one part of code I don’t quite get.
(my solution: here

The function that get’s called the button get’s clicked uses code like this:

handleButtonClick(key, song) {
      return() =>     { document.getElementById(key).play();
            this.setState({
                display: song,
            });}
    }

Where I expected that this would work:

handleButtonClick(key, song) {         
       document.getElementById(key).play();
            this.setState({
                display: song,
            })
    }

But this code tells me: document.getElementById… is null.
I really can’t see why this doesn’t work.

Thanks in advance anyway.

hey @sdbondt,

if you add an anonymous function to your onclick it should fix the problem or you can bind “this” to it. this is because you’re calling the function instead of passing the function to onClick so the function will run on every render instead of when you click.

  <button onClick={() => handleClick(drumKey, song)}>
  // or
  <button onClick={handleClick.bind(this, drumKey, song)}>
1 Like

Thank you very much, especially for giving me the 2 solutions.
Although I don’t quite get how and why it works like this, I understand the problem now and will be able to prevent this in the future.

1 Like

@sdbondt this article might help you understand a bit mate

1 Like