Image by Austin Neill from Unsplash
DESCRIPTION
onClick, onChange, onBlur... We usually pass a reference to the function handler but how do we add more arguments instead of just the event itself?
Preview
4 ways for event handlers in React
React
Summary
- The first function
handleClick
is accepting anevent
only as a parameter. We used it as a reference to theonClick
event handler. - The second function
handleClickCustomArguments
is acceptingname
only as a parameter. We used an anonymous function on theonClick
event handler and provided our customAdrian
string argument. - The third function
handleClickCustomArgumentsAndEvent
is accepting bothevent
andname
as parameters. We again used the anonymous function on theonClick
and provided theevent
and our customAdrian
string argument. - The fourth function
handleClickCurrying
is accepting bothname
andevent
as parameters (first we call the function with just name, thenonClick
will call the same function with the underlying event). We used a function call + function reference similar to the first example. The big difference is the Currying pattern to achieve the result. - All the event handlers have underlying events associated with them, when we pass a function reference to e.g.
onClick
it will call this function with an underlying event. You shouldn't pass a function call never, e.g.onClick={handleClick()}
as it would be wrong. However, you can use an anonymous function as we did to pass additional arguments or even skip the event entirely.