Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Home/Pills/ Pill - Event handlers arguments in React/
Home/Pills/Pill - Event handlers argum.../
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.
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...