1
import React, {useState} from "react";

function Todo({todo,index,removeTodo}){
    return(
    <div className="todo"> 
        {todo.text}


        <div>
            <button onClick={() => removeTodo(index)} > Remove </button>

        </div>
    </div>
    );
}

export default Todo;

Can someone explain why I need to put the () => before calling the function?

Joundill
  • 6,828
  • 12
  • 36
  • 50
mehCoder
  • 15
  • 3
  • `() => { /* function code */ }` is an anonymous function, it is similar to writing `function() { /* function code */}` except the anonymous function is automatically bound to the scope it is created in. Why the anonymous function is needed here is because `onClick` provides a React.MouseEvent parameter and not the index that `removeTodo` is expecting, therefore `removeTodo` needed to be wrapped to provide the expected parameter. – Jacob Smit Feb 05 '21 at 02:28
  • what is a react MouseEvent and why would it affect what I pass into removeTodo, would index not always just be a number? – mehCoder Feb 05 '21 at 02:49
  • `React.MouseEvent` is the Typescript type for a mouse related event in React. button's `onClick` has a type of `(event: React.MouseEvent) => void;`. It impacts how `removeTodo` is called as if you were to have `` then `removeTodo` would receive a React.MouseEvent and not an index. If you had `` the `removeTodo` would be executed during render and the return of the function assigned to `onClick` (which I assume is undefined). This leaves you with wrapping `removeTodo` in an anonymous function. – Jacob Smit Feb 05 '21 at 02:58

2 Answers2

0

take a look at this post: Correct use of arrow functions in React

Should be helpful. Be sure to reference the answer, not the question in the link above.

cloud712
  • 25
  • 1
  • 3
0

onclick is a native js event listener that requires a function and it passes an event object in it, if your removeTodo function is returning a function then it should work, but then your function should look like this:

function removeTodo(index) {

 return () => {}
}

which I don't think is a case.

DedaDev
  • 4,441
  • 2
  • 21
  • 28
  • so what your saying is that if I pass it in as just removeTodo it is an object, not a function? – mehCoder Feb 05 '21 at 02:37
  • Like this `onClick={removeTodo}` it's fine but then your `index` argument is an event object from click event, and like this `onClick={removeTodo(index)}` it is going to throw an error because you are assigning undefined to a function. – DedaDev Feb 05 '21 at 02:39
  • what do you mean by an event object, is it not just a number? – mehCoder Feb 05 '21 at 02:42