Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right name of event handler? onClick or handleClick?

I believe keeping code consistent is kind of important stuff. Sometimes I mess my code with different handler names (working with Javascript). What is the right name for event handlers? onClick vs handleClick?

like image 611
think-serious Avatar asked Feb 03 '20 22:02

think-serious


People also ask

How do you name an event handler?

Event handlers must have a name with the suffix EventHandler. The following example illustrates names that consist of the delegate name and the EventHandler suffix. Event handler naming conventions apply to pre and post event handlers.

Is onClick an event handler?

What is the onClick handler in React? The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app.

What does handleClick mean?

In the Toggle class, a handleClick method is defined as an instance method, which changes the local state. In the render method, this. handleClick is passed to the button as an event handler. Finally, do not forget to bind this to handleClick in the constructor.


2 Answers

This is subjective, but what you would see the most is the following:

  • if you are creating component and exposing event hooks, those props would be on: onClick, onHover, onUsernameChanged, onError. From inside your components, these props are just functions you call on some event. You don't care what they do, your job is to just call them at the right time
  • if you are consuming another component, you want to add handling in response to these events, so you use handle: handleChange, handleClick, handleUserLogout, because your job is now to handle some event and make something happen in response to it. If you don't handle, no changes to the app state will be made
like image 139
Max Avatar answered Oct 01 '22 01:10

Max


Serious,

According to : Naming-Event-Handlers-React. The autor of the page says :

For props:

We usually use the prefix with on*, as in onClick. This matches the built-in event handler convention. And by matching it, we declare that these props will house similarly-used event handler functions.

For the function names :

We follow the exact same pattern, but we replace on with handle*, as in handleClick.

I hope I was able to help you.

like image 44
Julien Jm Avatar answered Oct 01 '22 02:10

Julien Jm