Can't Bind Lambda to Event Without Shorthand (React)

<button onClick={function() {console.log("Clicked")}}
doesn’t seem to work, however…

<button onClick={() => {console.log("Clicked")}}
works perfectly fine.

Why is this the case? As far as I know, the shorthand is simply syntactic sugar for convenience, and doesn’t actually have any real difference compared to declaring anonymous functions with the function keyword.

Is this also the case in HTML?

There is no reason I can see why the normal function shouldn’t work. Post a live example on Stackblitz.

Not sure what you mean, but if all you have in the HTML is the function definition then clicking the button won’t do anything. It will run the code that defines the function but not actually invoke the function.

1 Like

Oops, didn’t bind so this was out of context, thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.