Home > Mobile >  Why doesn't React render an element without function invoked by arrow function unlike normal on
Why doesn't React render an element without function invoked by arrow function unlike normal on

Time:06-05

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>
);
})}

CodePudding user response:

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
  • Related