CodeNewbie Community 🌱

Sebastian9995
Sebastian9995

Posted on • Updated on

Manage event handlers in React

As of right now, React is the most popular library for building user interfaces. Its popularity can be attributed to several reasons, but mostly to the fact that it is very fast and does not take a lot of computational resources. It is also component-based, which means faster development speeds and less errors, thanks to compartmentalized design.

Building interactive web applications is more than choosing the right library. You need to manage those interactions themselves. In other words, you need handlers to capture user events and set up a response, so user interactions leads to changes on the screen.

In this article we’ll talk about handling events like clicks (on a button, container, or anything else), entering text into the field, submitting the form, and so on. By the end, you will learn how to handle events in React and why things are the way they are.

Understand event handling in React

You may know how to handle events using plain JavaScript in HTML, but React has its own spin on event handling. Instead of normal event object, event handlers accept an instance of SyntheticEvent, which is a wrapper around the normal event object that provides easy to understand interface and ensures consistency across browsers. That is why, when you create an event handler in React, it needs to accept at least one argument. React devs usually call this argument e or event. It contains information about the event as well as element that triggered it.

Event handler doesn’t need to accept an e argument. You can simply perform a certain task without using getting value in the input field in React.

Also the type of input is not limited to input fields or buttons. You can also use onchange to get value of a checkbox in React. More about that here:

https://simplefrontend.com/react-checkbox-onchange/.

Best event handling practices in React

Now that you know event handlers work, let’s look at practical use cases of using functions to handle user interactions.

Function Components and Hooks

Since their introduction in React v 16.8, hooks have become a life saver for many developers. Truth is, class component syntax is much more difficult to write and read. Functional components are simpler and now you can set them up to maintain a state.

Event handlers are typically used to store get users current input and store it in the state. Good news is that the useState method returns two values – the variable to hold state value, and the function to update it. This makes event handling easier, as you can simply call the function and pass it whatever value you want.

Usually current input value is stored in the e.target.value. Simply pass this value as an argument to the function and state will be updated. And the initial argument to the useState() hook will be set as default value of the state variable.

In contrast, class components require you to use the setState() method, which can be confusing. setState requires you to pass it an entire state object, even if you are changing only one property of the state. This can get confusing, but eventually you get used to it. Still, functional components’ solution is easier to write and for others to read as well.

In functional components you can also use the useEffect hook to manage side effects, like update title of the document whenever there’s a change to state.

Using arrow functions for event handlers

Arrow functions are relatively new to JavaScript, but their simplicity and straightforward behavior made them favorites for many React developers. For one, arrow functions’ this keyword is simply attached to the enclosing scope, so you don’t have to bind the function to its context. Combined with easier way to update state values, arrow functions in functional components often lead to code that is simpler and easier to read.

Smart use of event handlers

If you have several elements to listen for events, you can try to attach the event handler to the parent element instead. For example, attaching one event handler to the parent

    element will have the same effect as attaching it to every individual
  • child elements. This makes your app faster and more efficient. If you need to know which of the list items were clicked, you can use the getAttribute() method on event.target to get that information. In this case, you would have to pass ‘data-index’ as argument to get the number of list item that was clicked.

    Manually add event listeners in React

    JSX, the templating language for React, automatically supports most of the event handlers you will need. There’s even a way to implement onHover in React. But if the event listener you need is not available, you can add one using lifecycle methods or use the useEffect() hook for the same result.

    Ultimately, you are going to need the addEventListener method on the window interface. Keep in mind that it takes two arguments – the type of event you are listening for, and the function to handle it. Also don’t forget to remove the event listener when the app unmounts. That can be done by returning a function inside the useEffect() hook, or if you’re working with class components, the componentWillUnmount() lifecycle hook.

    Inline event handlers

    Component layouts are written in JSX, a template language for React. It looks like HTML, but JSX is actually JavaScript, and allows you to include dynamic expressions inside what looks like markup of your component. You can absolutely set inline event handlers, but experienced developers don’t do it because too much JavaScript code inside your JSX makes it difficult to read. And the entire point of using JSX is to keep things simple and avoid using top-level React API.

    Instead, its best to define event handlers outside of JSX and reference them in it. You can even pass down event handlers from parent components to child, and call method from another component in React. SimpleFrontEnd has great guide on this topic.

Top comments (0)