How does react know to provide the event as a second argument in the code below?
const clickMe = (parameter) => (event) => {
event.preventDefault();
// Do something
}
<button onClick={clickMe(someParameter)} />
Does it generate this to:
<button onClick={(event) => clickMe(someParameter)(event)} />
Or how does it work? Thanks.
Maybe this will help explain it a little better.
Closures are functions that carry the information (variables etc.) from their local environment with them when they're returned.
I'll work this example without arrow functions as they can be a little deceiving.
// `multplyBy` accepts a number as its argument
// It returns a new function that "remembers" that number
// when it's returned. But that new function *also*
// accepts a number
function multiplyBy(n) {
return function(n2) {
return n2 * n;
}
}
// So `multiplyBy(5)` returns a new function
// which we assign to the variable `five`
const five = multiplyBy(5);
// And when we call `five` with a number we get
// the result of calling 5 * 10.
console.log(five(10));
If you substitute multiplyBy(n) with clickMe(n) you'll see that you'll get a new function that gets used by the click listener, and the first argument of that function will always be the event.
Clickme variable in your code is a function which has return is function e => {...}. So when you specify like this:
<button onClick={clickMe(someParameter)} />
it is equivalent to
<button onClick={e => {...} />
which is basic form of a event handler in react