Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Image by Austin Neill from Unsplash

Event handlers arguments in React

Feb 9, 2021

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 an event only as a parameter. We used it as a reference to the onClick event handler.
  • The second function handleClickCustomArguments is accepting name only as a parameter. We used an anonymous function on the onClick event handler and provided our custom Adrian string argument.
  • The third function handleClickCustomArgumentsAndEvent is accepting both event and name as parameters. We again used the anonymous function on the onClick and provided the event and our custom Adrian string argument.
  • The fourth function handleClickCurrying is accepting both name and event as parameters (first we call the function with just name, then onClick 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.
logo with a rocket of the BigDevSoon application

Level up your Frontend skills

Code real-world projects based on Figma designs.
spread the word
Did you like this post? Share it with the world! 🌐