glenn zegers
glenn zegers

Reputation: 41

Is using "onClick={}" considered a bad practise?

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?

Upvotes: 2

Views: 3301

Answers (3)

Jonas Wilms
Jonas Wilms

Reputation: 138307

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.

Upvotes: 9

Vencovsky
Vencovsky

Reputation: 31645

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 mean onClick?

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.

Upvotes: 0

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4469

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.

Upvotes: 0

Related Questions