0

I am handling a button click in JavaScript. This below code is inside a class, by the way, I am using ReactJS library. Code:

 this.handleClick = (bipinValue)=>(event)=>{ console.log("button clicked "+bipinValue+" by this "+event.target.value)}

And inside render method of the same class. Code is below:

<button onClick={this.handleClick('bipin')} value="btn">Click me!<button>

Now my question I that what is this ()=>()=>{} Syntax in above code . I know only this ()=>{}, this is arrow function.

OUTPUT: button clicked bipin by this btn.

B4BIPIN
  • 353
  • 2
  • 11
  • 2
    Just a function that, when called, returns another function. Not a React thing. – CertainPerformance Oct 23 '18 at 07:26
  • 3
    Would it make more sense to you if it was written `(bipinValue => (event => { console.log("button clicked "+bipinValue+" by this "+event.target.value) }))`? – Amadan Oct 23 '18 at 07:30
  • but how it is giving bipinValue if it returned before running inner returned function? – B4BIPIN Oct 23 '18 at 07:32
  • Outer function is called during DOM creation (to set inner function as a handler), inner function is called on click. – Frax Oct 23 '18 at 07:45

1 Answers1

0

Overall, you created a function that returns a function.

To elaborate, you created a handler with the constant value "bipin" that will be passed on every click as well (on that specific handler). event.target.value will be the value attribute of the button at the time the click occurred.

The code this.handleClick('bipin') creates the function:

(event) => {console.log("button clicked bipin by this " + event.target.value)}

What might explain better what is actually going on here, is to see the code without arrow functions:

this.handleClick = function(bipinValue) {
    return function(event) {
        console.log("button clicked "+bipinValue+" by this " + event.target.value);
    }
}

Nothing weird, just JavaScript

Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33