0

I got a little bit of code that i can't quite wrap my head around. It's for a function that handles an onClick event in javascript/react:

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

Now I don't get why it does return () =>{} inside the body of handleButtonClick, but if I remove it, the code no longer works? I found nothing while googling this so any advice is welcome.

link to the project: https://codepen.io/koffiekan/pen/eYJqdWW

koffiekan
  • 3
  • 3
  • 2
    Apparently this method is expected to return a callback function. Why that is, would be up to how this method is used. – Taplar Jul 31 '20 at 23:15
  • Put the code where the handler is bounded to the event, my guess would be it is: Onclick = handleButtonClick(value,value); – Itay Moav -Malimovka Jul 31 '20 at 23:16
  • 1
    Given that the method name is `handleButtonClick`, one would expect there is some usage such as `someButton.addEventListener('click', handleButtonClick('somekey', 'somesong'))` – Taplar Jul 31 '20 at 23:16
  • @koffiekan I have an idea of what is your problem, regarding context access between fat arrow and regular functions, but I agree the question is too incomplete to provide an accurate answer. Would you mind sharing how you use the callback in your render method? – Maxime Helen Jul 31 '20 at 23:24
  • hi all, he the link to the project: https://codepen.io/koffiekan/pen/eYJqdWW – koffiekan Aug 01 '20 at 00:24

1 Answers1

0

This is called a callback. Here is a stackoverflow post on how they work. What is a callback function

onclick events are expecting a function, this is so that it can point or reference at the function when the event handler fires and does not need to copy the entire function - it allows the re-usability of the code.

Daniel
  • 639
  • 14
  • Callbacks have the form `function outer(callback){ callback(); }`. The code in the question is just a function that returns another function; it doesn’t call it. – Sebastian Simon Aug 01 '20 at 00:56