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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With