Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Passing functions as props

I have a question concerning passing functions as props. In the tic-tac-toe tutorial (https://facebook.github.io/react/tutorial/tutorial.html) at the end the Game component passes the onClick handler as such:

<div className="game-board">
  <Board
    squares = { current.squares }
    onClick = {(i) => this.handleClick(i) }
  />
</div>

First, why cant we pass the function like this instead:

onClick = { this.handleClick(i) }

And I understand that passing "i" is important but something in the middle of the tutorial confused me:

return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />;

Here we don't pass "i" in the parenthesis of the arrow function. I don't want to write too much to make the question less verbose. I am sure some people have gone through this tutorial and will be able to give an answer my questions.

UPDATE: Tnx everyone for the brief and helpful answers. As a follow-up, in the official docs, we are told to bind a function if it is to be used as an event handler for a component. Why is this necessary and how come it was never used it the tutorial?

like image 272
Gilbert Nwaiwu Avatar asked Dec 19 '16 11:12

Gilbert Nwaiwu


People also ask

Can we pass functions as props in React?

Define the function in the parent component. Pass it as a prop to the child component, e.g. <Child handleClick={handleClick} /> . Use the function in the child component.

How do you pass a function as props in React functional component TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

How do you pass a function from one component to another in React JS?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.


1 Answers

This doesn't pass the function (it calls the function before binding to onClick):

onClick = { this.handleClick(i) }

Alternatively, you could bind:

onClick = { this.handleClick.bind(null, i) }

But the arrow function seems clearer to read (at least IMHO).

For the second issue, the i is a parameter for handleClick, not onClick. onClick does have parameters (the first being the event object), but in this case, you don't need anything from the onClick parameters, so they are left empty.

like image 103
Davin Tryon Avatar answered Sep 18 '22 15:09

Davin Tryon