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
handleClickis accepting aneventonly as a parameter. We used it as a reference to theonClickevent handler. - The second function
handleClickCustomArgumentsis acceptingnameonly as a parameter. We used an anonymous function on theonClickevent handler and provided our customAdrianstring argument. - The third function
handleClickCustomArgumentsAndEventis accepting botheventandnameas parameters. We again used the anonymous function on theonClickand provided theeventand our customAdrianstring argument. - The fourth function
handleClickCurryingis accepting bothnameandeventas parameters (first we call the function with just name, thenonClickwill 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.
onClickit 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.
