Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick anonymous function with arguments vs onClick(function(arguments))

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?

like image 614
Magofoco Avatar asked Jan 25 '23 19:01

Magofoco


1 Answers

onClick accepts a callback i.e. a function that will be called when the button is clicked.

  1. anotherClick is a function so it works, as it's being called properly
  2. () => anotherClick() is equivalent to this
...
const myTempFunction = () => {
  anotherClick();
}
...
onClick={myTempFunction}

Since you're ultimately passing a function to onClick it works

  1. () => handleClick(myValue) same reason as above, and equivalent code is
...
const myTempFunction = () => {
  handleClick(myValue);
}
...
onClick={myTempFunction}
  1. 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

like image 67
Shadab Avatar answered Jan 27 '23 07:01

Shadab