What is the right name of event handler? onClick or handleClick?
I prefer naming event props/attributes on*
and handlers handle*
.
The reasoning for that is simple, otherwise sometimes they clash. Take a look at this example:
const Foo = ({ onClick }) => {
const handleClick = (event) => {
doSomethingElseHere();
onClick(event);
}
return (
<button onClick={handleClick}>Bar</button>
)
}
If we named both the handler and the prop onClick
, their names would clash.
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.
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