1

I am learning React, and followed this tutorial to create a simple Tic-Tac-Toe game that you can view here in CodePen.

I am confused about how the arrow function works in the onClick property of the Square component that is being returned inside of the renderSquare function of the Board component: onClick={() => this.props.onClick(i)}. And also again similarly the Game component where I have onClick={ (i) => this.handleClick(i)}. I assumed I could write it without the arrow function (just like onClick={this.handleClick(i)}) but this breaks the game.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
Attila
  • 1,097
  • 2
  • 19
  • 45
  • Rough explanation: `onClick` takes a function that is executed on event trigger. When `() => this.foobar(blah)` is done, that *creates an arrow function* that executes `foobar` with arguments `blah`. The reason you can't do `{this.foobar(blah)}` is because that will execute the function and pass the return value. `onClick` needs a function execute, not a value. – Andrew Li Jan 17 '17 at 03:00
  • see this: http://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method – Jayce444 Jan 17 '17 at 03:00
  • You might also want to have a read https://facebook.github.io/react/docs/handling-events.html – Calvin Jan 17 '17 at 03:01

1 Answers1

6

onClick expects a function. An arrow function does not have its own this; the this value of the enclosing execution context is used. Arrow function is a replacement for the following

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

It doesn't work when you run it like

onClick={this.handleClick(i)} 

because in this case it will call a function and that will pass a return value that will be evaluate everytime render is called. So if you are doing somethings in the onClick function that causes a rerender for instance setState you app will go in an endless loop. Thus onClick needs a function and not a value so unless you are returning a function from the onClick handler you should not directly call it.

Arrow function above performs the role of binding the parameter to the function

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • I think this conclusion cannot be reached without knowing what is inside the `handleClick`, it might as well give you a new function callback back as a value. Ofcourse it fits the question, but it really depends on what the `handleClick` function is doing – Icepickle Nov 23 '17 at 08:45
  • @Icepickle, yes you are right, This is an old answer of mine which didn't have that explanation, I was in the process of editing it with more details. – Shubham Khatri Nov 23 '17 at 08:51