CodeNewbie Community đŸŒ±

aagya11
aagya11

Posted on

Event handling in React

Understanding events is incredibly important for building interactive applications. There can be many different types of events – from common mouse clicks to scroll and even events that allow you to capture touch screen activities from users on their smartphones. Every user interaction is technically an event, and React allows you to customize your app’s response to these events, thus building an interactive web app.

It probably shouldn’t come as a surprise that React has its own unique way of handling events. The library uses SyntheticEvent wrapper, not the Event interface that is native to most browsers. SyntheticEvent is essentially the same, only with some improvements in consistency across different browsers. React has a number of built-in event handlers, you can see the list here. But it also allows you to add window events that are not built-in.

This article will take you through event handling with React. Respond to input events and validate fields to display helpful feedback. We will also closely examine SyntheticEvent and how to work with it to achieve desired results.

Get event data from SyntheticEvent

As you can probably guess, working with user inputs is an important aspect of building interactive apps with React. With click events it’s simple – the user either clicks a button or some other element or not. When it comes to text fields, select dropdowns, and similar inputs, things get a bit tricky. Sometimes responding to these events requires us to know what the user typed in, or what option they chose from select dropdown. We can access this information in SyntheticEvent. This article details how to get values from text input in React.

For starters, let’s discuss an example where an element accepts user input. Then we set its onChange event handler to dynamically validate what the user has typed in. For example, if the application asks user to enter their email, we would have to validate that the current input field is above certain length and includes the ‘@’ symbol.

Once you’ve created the input element, you can set event handlers directly inside JSX. The syntax is pretty similar to how you’d set event handlers using plain JavaScript code. Except one difference – prop names (attribute names) for event handlers are camelCased in React. For example, onchange becomes onChange.
SyntheticEvent is fairly simple and easy to work with. If you’re familiar with Event object in native web development, you likely won’t struggle with SyntheticEvent either.

Let’s get back to our example of input field that asks users to enter their email. When it comes to input elements, most often you are going to use the onChange event handler, which triggers every time users enter something new, or delete whatever is already in the field. Every time this happens, you can define an event handler that accesses most recent input value, so you can keep track of all changes in the field. Usually React developers store current value of input field in the state.

React devs often use shorthand e to access SyntheticEvent. All event handlers receive SyntheticEvent that contains information about the event that just occurred. So it’s safe to pass them argument e and assume it’ll be SyntheticEvent. e.target.value will give you current value in the input field, which you can use to do various operations. Here is an article that further explores how to get input values.

At the same time, your input field needs to get its value from the state. In this case, entering something into the input field updates the state, which in turns updates value of the input field. This is great for consistency, and since state is a normal JavaScript object (variables in case of functional components) this makes it easy to validate input field values as well.
To make sure the input field contains a certain value, you could use the indexOf() method and see if the symbol is found in the input field. Remember that if the method returns -1, then the specified piece of string can not be found.

onClick

Click is another very common event you may need to handle in React. You can set onClick event handler not only on buttons, but also on elements that offer more customization, as well as containers. In my time as a React developer, I’ve seen some creative uses for the onClick event handler, so the only limit is your imagination.

Simply put, event handler for onClick will execute whenever user clicks a specified element. You can either define an event handler function and reference it inline in JSX. If the click event handler is simple, you can even define what you want it to do within JSX.

Let’s look at an example:

console.log(“button was clicked”}> Click Me </ button >
In this simple example, whenever users click the button, it will log the message ‘button was clicked’ to the console. Note that curly braces are necessary to tell React to interpret value of the onClick parameter as a dynamic JavaScript expression. Also note that you don’t immediately enter what you want React to do when user clicks the button. Instead, event handler is a function that, in its body, performs a certain action. This is an important distinction that ensures that action is performed only when a certain event occurs.

onSubmit

Most of the events happen in relation to forms in React. Forms are collection of inputs and buttons. The submit event, in general, allows you to differentiate between events in individual input elements vs the form as a whole. onSubmit event handler is usually set on the

element itself, and triggered by clicks on the button inside the form. Note that the button must have a type of ‘submit’.

In onSubmit event handlers you often use e.preventDefault() to keep browser from manually refreshing the page. As you know, React apps are SPAs (single page applications), so the refresh is unnecessary.

Summary

With that, hopefully you learned something new about handling events in React.

Top comments (0)