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 > 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 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.
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
Top comments (0)