0

In JSX, what is the difference between this

<div onClick={this.someFunction} />

and

<div onClick={() => this.someFunction()} />

and also, when is one recommended over the other in an onClick event?

I have had a look at this but it is not answering my question really.

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
Siya Mzam
  • 4,655
  • 1
  • 26
  • 44
  • 1
    Both examples use a function reference. – connexo Feb 25 '18 at 08:56
  • Okay, thanks. So are you saying those are both the same just different syntax? – Siya Mzam Feb 25 '18 at 08:58
  • 1
    Exactly. Your second code example just is more bloated and less readable. – connexo Feb 25 '18 at 08:59
  • If it's about react, take a look at [this](https://stackoverflow.com/questions/47679673/how-does-event-handlers-with-arrow-functions-achieve-context-binding) – Kirill Simonov Feb 25 '18 at 09:04
  • @KirillSimonov, thanks, that actually helped a lot in clearing the confusion. So it seems to me that the two ways mentioned above are actually different and not the same as connexo said. – Siya Mzam Feb 25 '18 at 14:23

1 Answers1

0

No there is a difference, first one won't work with onchange but second one work fine, because second one bind this with class automatically, first one don't .

radhey shyam
  • 759
  • 6
  • 9
  • Oh well, first this is about `onClick` not `onChange` and binding is not the issue here. For instance the binding could have been done at constructor level – Siya Mzam Feb 25 '18 at 14:19
  • They actually don't. It seems that the first example will pass a reference to the function and the second one will pass the return value of that function. – Siya Mzam Feb 25 '18 at 18:49