Few concepts are more important to React than event handlers. In simple words, these are functions that run when an events – click, submit, focus, keydown – happen. Essentially, event handlers are a key to letting users interact with your web app and receive the desired response.
Let’s use onClick as an example, as it is the simplest. This event handler lets you call and execute a function whenever users click a button. Without the event handler, React web applications would be severely limited in their interactive features.
Event handlers are not exclusive in React. Most likely, you are already familiar with onclick and other event handlers used in normal HTML. React event handlers are a little different – as they respond to synthetic events. This is a wrapper around native browser events that provides additional features.
Without further ado, let’s see how to create event handlers to respond to different events (clicks, hovers).
onChange
As the name might suggest, onChange responds to change events in React. It is usually set on input elements to detect whenever input changes. For example, onChange will notice and run the event handler if user changes its selection in the dropdown, or enters a new value into the input field. This also applies to default values for select dropdowns in React. This tutorial delves deeper into this question.
This is one of the most commonly used events in React, so the library has built-in support for it.
The onChange event handler is often used to update the state variable. If the input element gets its value from the state, this creates a sort of two-way binding. Input gets its value from the state, and changes in the input also update the state.
Like every event handler, onChange accepts one required argument – reference to SyntheticEvent. This is an object that contains data about the event and the element that triggered the event. When you use onChange to update state value, you can access current input value on e.target.value, assuming that you use e as a stand-in for SyntheticEvent.
When you have complex forms, it’s not unusual to create multiple input fields and set onChange event handlers on them.
One important difference between onChange React event handler and HTML onchange is that the former triggers every time user enters something into the field (or deletes it). HTML version of the event handler triggers only when the user has finished typing.
onSubmit
It’s impossible to create forms in React without using the onSubmit handler. onSubmit triggers whenever users click a button within the form, or a button that has type of ‘submit’. React developers use this handler to do a number of things after user submits the form. For example, have you noticed how, sometimes after you submit the form, you are redirected to the homepage? That’s because of the onSubmit event handler.
This event handler is also useful to prevent browser’s default behavior. For example, when working in React, usually you don’t need to refresh the page after user submits the form. You can use the preventDefault() method on synthetic event to achieve this. Developers also often use it to validate user inputs before submitting them.
Here's a basic example:
`function MyForm() {
function handleSubmit(event) {
event.preventDefault(); // Prevents page refresh
// Do something with the form data
}
return (
{/* Form inputs go here */}
Submit
);
}`
In this case, handleSubmit runs every time the form is submitted. Calling the event.preventDefault() method prevents the default form submission behavior, which is to reload the page.
You can set onSubmit event handler to an inline function or you can define a function outside of JSX and reference it in your JSX. If you have a complex event handler, it’s always better to define it outside of JSX.
You can use the onSubmit event handler to implement user-friendly features, like reset form after it is submitted. In this case, you will have to work with state values. Tutorial on SimpleFrontEnd explains this very well.
onClick
onClick is probably the most common event handler used in React. It allows you to specify a function that should be called every time user clicks on a certain element. For example, you might want to set scroll position every time user clicks on a button. Here's a guide that explains how to do that.
Usually it’s set on elements, but sometimes also on elements like .
In native code, onClick is onclick. But to differentiate React event handlers from HTML, we use camelCase instead. In JSX, onClick prop accepts a function value, not a string like in HTML.
Event handlers for click event can be as simple or as complex as you want. Like other event handlers, you can either directly pass an inline event handler in JSX or pass name of the function created outside of JSX.
onFocus
onFocus event handler responds when a certain element enters into focus. That can happen when user clicks on the element (like input) or uses keyboard to focus containers and other normal elements.
Normal browsers usually respond to onFocus event – input becomes highlighted with a border and cursor starts ticking.
onFocus is certainly useful to improve UX of the app. For example, you can customize how the input element is highlighted. You can also customize the placeholder when user focuses on input field.
In native browser, web developers use focusin and focusout events to respond to focus and removal of focus events. In React, these event handlers translate to onFocus and onBlur. The former corresponds to focusin, and the latter responds to focusout.
You can use onFocus event handler to perform useful side effects. For example, set focus on input field when user clicks a certain button.
In TypeScript, the type for onFocus event handler is FocusEvent.
onKeyDown
Finally, onKeyDown event handler allows you to run a function when users press one of the keys. Therefore it has many use cases for handling user inputs. It is also more customizeable than other event handlers. You can specify one of many keys to respond to. You can use this to validate user inputs, and increase overall interactive features. For example, submit the form when users click ‘Enter’.
React developers often use onKeyDown to update the state when users click a specific button.
As usual, the event handler accepts SyntheticEvent argument. In case of onKeyDown, this object contains information about the specific pressed button. You can write an if condition that checks which button was pressed down, and run a function for specific buttons.
onKeyDown works a little differently on elements that are not naturally interactive, such as
. This is because containers and other such elements are difficult to focus on. To make onKeyDown work, developers must add the tabIndex attribute. Then element can be focused and you can start listening for onKeyDown events.It should be noted that there are some exceptions to onKeyDown event. Keys like ALT, CTRL, and SHIFT don't fire this event. You can work around this by listening to keypress or keyup events instead.
Summary
In this article, we discussed most common event handlers used in React. If you’re planning to build an interactive web applications, you can’t escape using these event handlers.
Top comments (1)
Crafting compelling and descriptive title tags for each page that accurately represent the content.