I learned that using onclick
is considered a bad practise in HTML. Right now I'm going through a React tutorial. The tutorial uses <button onClick={shoot}>Take the Shot!</button>
. Is this also considered a bad practise in React? And if it is, what is the "right" way to do it?
I learned that using onclick
is considered a bad practise in HTML. Right now I'm going through a React tutorial. The tutorial uses <button onClick={shoot}>Take the Shot!</button>
. Is this also considered a bad practise in React? And if it is, what is the "right" way to do it?
onClick
in React, not about the DOM API.
– VLAZ
Commented
Jul 26, 2019 at 13:42
onclick
don't work.
– Vencovsky
Commented
Jul 26, 2019 at 13:46
onClick
HTML attrivute (well, more React-ified) as in it's case-insensitive but it seems it's not.
– VLAZ
Commented
Jul 26, 2019 at 13:48
The onclick
attribute in HTML is considered a bad practice because it decouples the function from the place where it was called from (among other things). If you read through the related JS files, it is unclear where a certain function was called from, and therefore its purpose is unclear. If you use .addEventListener
from within JS, you keep the function and the purpose (the events that trigger it) together.
Reacts purpose is to keep the logic and the view together, so there is no decoupling possible at all. Therefore it is totally fine to use onClick
, and it's the only right way I can think of.
No, in React is the usual way to handle a click event. It is not a good practice to do something like <button onClick={() => some_code_here}>Foo Bar</button>
because, in this way, you declare a new function on every render.
Just adding more information about the differences of onclick
and onClick
.
In react, onclick
won't work and onClick
is handled by react as you can see in this sandbox.
When using onclick
it might also give you a warning
Warning: Invalid event handler property
onclick
. Did you meanonClick
?
There is some reasons why onclick
is a bad practice, but in react, the correct way of handling clicks is passing a function to onClick
prop.