Handling Events

User events are crucial in creating an interactive web application.

In a previous article, we introduced "state", and with that power, we can start creating more sophisticated applications by responding to events.

By events, we mean representing the user's interactions with the interface, like clicking a button, submitting a form, updating an input, or scrolling the page.

React provides a robust system to handle these events in an easy-to-understand and efficient way once you learn the patterns.

This article provides a brief overview of user events in React.js.

Handling Events

Event Handlers

Events are handled through special functions called event handlers.

These JavaScript functions get called in response to a specific event. Event handlers are passed as props to elements that can trigger events.

For instance, when we created our Counter component in our state example, we responded to the onClick event.

And to remind you, here's an example of how we add an event to a button that is triggered when the user clicks the button (which is passed to the onClick prop):

function handleClick() {
  alert('You clicked the button!');

<button onClick={handleClick}>Click me!</button>

In this example, handleClick is the event handler for the onClick event. When the button is clicked, the handleClick function is called, and we get an alert message with "You clicked the button!'".

It's a typical pattern for shorter once-off functions to directly in-line them on the onClick with an arrow function.

Here's an example of how we could shorten this by embedding our function directly in our JSX:

<button onClick={() => alert('You clicked the button!')}>
  Click me!

Common mistake

A common mistake with events is calling the function or forgetting to wrap it:

// ❌ Wrong way! Immediately executing the alert
<button onClick={alert('You clicked the button!')}>
  Click me!

// ❌ Wrong way! Immediately calling the function
<button onClick={handleClick()}>
  Click me!

And this is because rather than executing the code, we want to pass a function to be called later (to "handle" the event).

Synthetic Event Object

React wraps the native browser events into instances of SyntheticEvent. This wrapper provides a consistent interface for events across different browsers, as native events can behave differently between different browsers. SyntheticEvent has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

So if you are used to handling events in JavaScript, you should find it easy to use the events in React.

Event Object

Each event handler receives an event object as its first argument. This event object contains information about the event, such as which element triggered it, the state of the keyboard keys, and more.

Let's consider an example where we use the onChange event to capture and display the text a user types into an input field:

import { useState } from 'react';

function WhatDidYouType() {
  const [inputValue, setInputValue] = useState('');

  function handleOnChange(event) {

  return (
      <input type="text" onChange={handleOnChange} />
      <p>You typed: {inputValue}</p>

In this example, event.target.value gives the current text entered in the input field. handleOnChange is the event handler for the onChange event.

When the text in the input field changes, the handleOnChange function is called, updating the state with the new text and triggering a re-render to display the new text.

So whenever we type or delete a character in our input, we should immediately see the <p>You typed: </p> updated on screen.

Whenever I stumble across an event I haven't used before, I usually console.log the event to better understand what's in it that might be useful.


Check your understanding with this debugging challenge!

I've set up a CodeSandbox here that contains two challenges.

  1. In the Button.js file, find the bug that stops the alert from working properly.
  2. In WhatDidYouType.js, wire up an event to display what the user is typing.


Ask questions in our Discord chat or in the comments below if you get stuck.

You can join Discord by signing up for an account here on Codú for FREE, and we will email you a link.

In the next article, we will learn how to synchronize a component with an external system using a Hook called useEffect.

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.