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?

- 31
- 5
-
`onclick` or `onClick` ? In react, you should always use `onClick` with capital letter `C` – Vencovsky Jul 26 '19 at 13:39
-
@Vencovsky are they different? – VLAZ Jul 26 '19 at 13:39
-
1Possible duplicate of [onclick or onClick?](https://stackoverflow.com/questions/4380719/onclick-or-onclick) – ravibagul91 Jul 26 '19 at 13:40
-
2@ravibagul91 I don't think this is relevant to this question. This is asking if you should use `onClick` in React, not about the DOM API. – VLAZ Jul 26 '19 at 13:42
-
1@VLAZ yes, check [this sandbox](https://codesandbox.io/s/mystifying-galileo-fj6p8), you will see that in react, `onclick` don't work. – Vencovsky Jul 26 '19 at 13:46
-
I used `onclick` for the HTML attribute. `onClick` is what my question is about, about React. – glenn zegers Jul 26 '19 at 13:47
-
1There's a whole [Handling Events](https://reactjs.org/docs/handling-events.html) section in the react docs that would have answered this for you – charlietfl Jul 26 '19 at 13:47
-
1@Vencovsky thanks, I not too proficient in React. My first thought was that it's the same as the `onClick` HTML attrivute (well, more React-ified) as in it's case-insensitive but it seems it's not. – VLAZ Jul 26 '19 at 13:48
-
related: https://stackoverflow.com/q/5871640 – djvg May 02 '23 at 15:22
3 Answers
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.

- 3,228
- 1
- 23
- 44

- 132,000
- 20
- 149
- 151
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.

- 4,103
- 1
- 12
- 21
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.

- 28,550
- 17
- 109
- 176