I would like to know why in certain types of events, such as onClick
, I have to declare an anonymous function to execute the onClick
if my function contains arguments.
Example: https://codesandbox.io/s/suspicious-ramanujan-v998u
export default function App() {
const myValue = "MY VALUE";
const handleClick = (anyString) => {
console.log(anyString);
};
const anotherClick = () => {
console.log("It works");
};
return (
<>
<Button onClick={() => anotherClick()} color="primary">
Works without arguments <-- Works
</Button>
<Button onClick={anotherClick} color="secondary">
Works without arguments <-- Works
</Button>
<Button onClick={() => handleClick(myValue)} color="primary">
Works with arguments <-- Works
</Button>
<Button onClick={handleClick(myValue)} color="secondary">
Does NOT work with arguments <-- Does NOT work
</Button>
</>
);
}
Question I do not understand why I have to create an anonymous function if the function I want to execute has arguments.
Why do I have to do onClick={() => handleClick(myString)
}?
Why onClick={handleClick(myString)}
is not enough?
onClick
accepts a callback i.e. a function that will be called when the button is clicked.
anotherClick
is a function so it works, as it's being called properly() => anotherClick()
is equivalent to this...
const myTempFunction = () => {
anotherClick();
}
...
onClick={myTempFunction}
Since you're ultimately passing a function to onClick
it works
() => handleClick(myValue)
same reason as above, and equivalent code is...
const myTempFunction = () => {
handleClick(myValue);
}
...
onClick={myTempFunction}
handleClick(myValue)
, now here you're actually calling the function the you're passing the value that the function returns to onClick
, not the function itself,
the equivalent code would be...
const myResult = handleClick(myValue); // This is the result of calling the function
...
onClick={myResult} // myResult isn't a function, it's the return value of handleClick(myValue)
Since you're not actually passing a function to onClick
, onClick
can't be called and it doesn't work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With