0

Why does this work?

<span onClick={()=>removeTodo(index)}>x</span>

But this doesn't work?

<span onClick={removeTodo(index)}>x</span>

Full code

{todo.map((item, index) => {
  return (
    <pre className={index} key={index}>
      <h1 id={array}>{item}</h1>
      <span onClick={()=>removeTodo(index)}>x</span>
    </pre>
);
})}
  • Does this answer your question? [Onclick calling functions diffrences](https://stackoverflow.com/questions/71245336/onclick-calling-functions-diffrences) – pilchard Jun 04 '22 at 12:32
  • Because the function is executed instantly when the JSX is compiled. So the `removeTodo(index)` is being replaced by its return value, which is most likely `undefined` (void). – HynekS Jun 04 '22 at 12:32
  • also: [onClick anonymous function with arguments vs onClick(function(arguments))](https://stackoverflow.com/questions/63455337/onclick-anonymous-function-with-arguments-vs-onclickfunctionarguments) – pilchard Jun 04 '22 at 12:33
  • Functions are data types in JavaScript and just like you can't give a `boolean` where you expect a `string`, you can't pass a `string` where you expect a function. `onClick` expects a function to be executed later and assigning the result of a function invocation to it will only work if the function returns another function, which your function probably doesn't. Note that you don't HAVE to pass an arrow function or a NEW function, you can also pass the existing function by name, like `removeTodo`, but due to arguments to the function this is not always possible. – fast-reflexes Jun 04 '22 at 12:52

1 Answers1

2

The onClick function requires a short hand function syntax ()=>{} especially when you are calling a function and passing the parameters at the same time. It is also used when you are calling multiple functions inside onClick.

When to Use ()=> in onClick?

  1. Calling a function with a parameter
  2. Calling multiple function in a single onClick
  3. Providing a function definition inside onClick

When not to use?

  • Calling a function without a parameter
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
markcalendario
  • 218
  • 2
  • 9