I'm confused by this when doing event handling in javascript with ReactJS.
Is there any differences between
<button onClick={f()} />
and
<button onClick={()=>f()} />
what I know is the second one is a wrapping function that return f(), but i don't see what exactly changed there. And I do see both of them in others' code.
I'm confused by this when doing event handling in javascript with ReactJS.
Is there any differences between
<button onClick={f()} />
and
<button onClick={()=>f()} />
what I know is the second one is a wrapping function that return f(), but i don't see what exactly changed there. And I do see both of them in others' code.
Share Improve this question asked Nov 8, 2018 at 1:48 daryldaryldaryldaryl 833 bronze badges 2- Nice question, I've seen a lot of people having this exact error. – Mark E Commented Nov 8, 2018 at 2:37
-
I think I heard somewhere that onClicks sometimes get triggered accidentally on render if you have an
onClick={f()}
so some people useonClick={(event) => f(event)}
to prevent it and accessevent.preventDefault()
– fvaldez421 Commented Nov 8, 2018 at 7:56
3 Answers
Reset to default 7In your example, the first case just calls f
at load time, which is probably not what you want unless f
returns another function (which would be called when a click event occurs). The second is just an anonymous function wrapping f
so that f
is not called until the click
event happens.
Why is the second notation useful?
If f
takes no arguments then using
<button onClick={ f } /> // note: no parentheses
and
<button onClick={ () => f() } />
are pretty much equivalent. There is a slight difference between the two in that the event
is passed to f
in the first case and is not in the second. Technically <button onClick={ event => f(event) }/>
would be equivalent to the first case, but this is somewhat beside the point.
However, if f
does take some arguments (other than the event
itself), then it's useful to use:
<button onClick={ () => f(someValue) } />
so that someValue
can be passed to f
when the click event happens.
The difference between these two is the first one,
onClick={f()}
means that the return value of the f
function will be executed on the onClick event.
Whereas the second example,
onClick={() => f()}
will execute the function f
itself on the onClick event.
The problem isn't specific to React and onClick
. It's applicable to any case in JavaScript where a function may be expected or not.
The difference between them is that one is a function while another one may not be a function.
If the result of f()
is not a function and a function is expected then this is a mistake, like in onClick={f()}
.
() => f()
is a function. If it's used where a function is not expected then this is a mistake, like in (() => f()) + 1