Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 33

Handling Events in React

Recommended resources

Hello! Welcome to the first lesson in our new module, "Forms and Event Handling." In the previous module, we took a deep dive into the useEffect hook, mastering how to handle side effects, manage asynchronous operations, and debug common issues. You now have a solid foundation for controlling what your components do after they render.

Now, we'll shift our focus from the component's lifecycle to its interactivity. How do we make our applications respond to user actions like clicks, keyboard input, and form submissions? This is where event handling comes in.

This lesson will introduce you to React's event system. By the end, you'll be able to handle user events in React using synthetic event handlers. We'll cover what these "synthetic events" are, why React uses them, and how to use them to bring your components to life.

Let's begin.

1. Making Components Interactive

In vanilla JavaScript, you might use element.addEventListener('click', ...) to make an element interactive. React abstracts this away with a more declarative approach. Responding to events in React is a simple two-step process:

  1. Define an event handler function: This is a function that will run in response to a user interaction.
  2. Pass the handler to a special JSX prop: These props are named on<EventName>, following a camelCase convention (e.g., onClick, onSubmit, onMouseEnter).

The following video provides a clear, practical demonstration of this process.

React 19 Tutorial - 15 - Event Handling

This video from Codevolution introduces the fundamental pattern for handling events in React.

Please watch from the beginning to 03:05. Pay attention to: The standard convention for naming event handler functions (e.g., handleClick). How to assign the handler function to the onClick prop. The option to define the handler inline as an arrow function.

As you saw, you can create a CustomButton component like this:

// In CustomButton.tsx

const CustomButton = () => {
  // 1. Define the event handler function
  const handleClick = () => {
    alert('Button was clicked!');
  };

  return (
    // 2. Assign the handler to the on<Event> prop
    <button onClick={handleClick}>
      Click Me
    </button>
  );
};

export default CustomButton;

2. A Critical Distinction: Passing vs. Calling

This is one of the most common mistakes for newcomers to React. Notice the syntax in the example above:

  • Correct: <button onClick={handleClick}>
  • Incorrect: <button onClick={handleClick()}>

When you write {handleClick}, you are passing a function reference. You are telling React, "Here is the function I want you to execute when the user clicks this button."

When you write {handleClick()}, you are calling the function immediately during the render process. The return value of the function (in this case, undefined) is then passed to the onClick prop. This means the alert would pop up the moment the component renders, not when the user clicks.

The video you just watched highlights this exact point. It's a crucial detail to internalize.

React 19 Tutorial - 15 - Event Handling

Let's revisit the Codevolution video for a direct comparison of these two approaches.

Watch the segment from 03:05 to 04:11. The presenter clearly demonstrates why adding parentheses () causes the event handler to fire at the wrong time.


3. Under the Hood: React's SyntheticEvent System

When you attach an event handler like onClick, the event object your handler receives isn't the raw browser event. Instead, it's a SyntheticEvent. This is a cross-browser wrapper around the native event, created by React to ensure that events work identically across all browsers.

This is a key architectural decision in React, and given your interest in the "deep theory," it's worth understanding why.

React: Understanding React's Event System

This article from dev.to provides an excellent explanation of what Synthetic Events are and the performance optimizations behind them.

Please read the following sections: 'What is a Synthetic Event?': This defines the core concept. 'Working Principle of Synthetic Events': This explains the two key performance optimizations: Event Delegation (attaching all listeners to the root) and Event Pooling (reusing event objects to reduce memory allocation). This is analogous to memory management strategies seen in lower-level systems programming. 'Why does React Choose Synthetic Events': This summarizes the benefits.

To summarize, React's SyntheticEvent system provides:

  • Cross-Browser Consistency: It smooths out inconsistencies in how different browsers implement their native event systems. An event.target will behave the same in Chrome, Firefox, and Safari.
  • Performance: By using event delegation, React avoids attaching thousands of event listeners in a large application. Instead, it uses a single listener at the root of the app, which then determines which component was the target. Event pooling further boosts performance by recycling event objects.

This image shows a SyntheticEvent object logged to the console. You can see how it wraps the native event and contains a wealth of information.

React Synthetic Event Structure and Handling in CodePen
This image shows the structure of a `SyntheticEvent` for a form submission. The console reveals properties like `target`, which points to the form element, and other details provided by React's event wrapper.

4. Interacting with the Event Object

The SyntheticEvent object passed to your handler has a familiar API, largely mirroring the native browser event. Here are the most important properties and methods you'll use.

event.preventDefault()

Prevents the browser's default action for an event. The most common use case is in a form's onSubmit handler to stop the browser from performing a full-page reload.

function MyForm() {
  const handleSubmit = (event) => {
    // Prevent the default browser behavior of reloading the page
    event.preventDefault();
    console.log('Form submitted without a page refresh!');
    // You would typically handle form data submission here
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

event.stopPropagation()

Stops the event from "bubbling" up the DOM tree to parent elements. This is useful in complex UIs where a click on a child element shouldn't also trigger a click handler on its parent.

event.target and event.currentTarget

  • event.target: Refers to the specific DOM element that initiated the event (e.g., the exact <button> the user clicked).
  • event.currentTarget: Refers to the DOM element to which the event handler is attached.

In many simple cases, these will be the same. But if you have nested elements, event.target could be a child, while event.currentTarget remains the parent where onClick was defined.

The dev.to article you read earlier has clear examples for all these methods.

React: Understanding React's Event System

Let's refer back to the 'React: Understanding React's Event System' article for code examples of these common methods and properties.

Review the section 'API and Usage of Synthetic Events'. It provides practical code snippets for preventDefault(), stopPropagation(), target, and currentTarget.


5. Common Event Handler Types

React supports a wide range of synthetic events. You can find a complete list in the React documentation or by inspecting the TypeScript types, but here are the ones you'll encounter most frequently:

Category Event Handlers Use Case
Mouse Events onClick, onDoubleClick, onMouseDown, onMouseEnter, onMouseLeave, onMouseMove Responding to clicks and mouse movements.
Form Events onChange, onSubmit, onInput Handling form input and submission.
Keyboard Events onKeyDown, onKeyUp, onKeyPress Capturing keyboard strokes.
Focus Events onFocus, onBlur Detecting when an element gains or loses focus.

This image provides a simple, visual example of an onClick handler in a React component.

React Synthetic Event Handling with TypeScript
This screenshot shows a basic React component using `useState` and an `onClick` handler. The `onClick` prop on the `<button>` element is set to the `btnHandler` function, which updates the component's state.
Test your understanding!

You are building a simple search component. When the user clicks the "Search" button, you need to prevent the form from reloading the page and log the text from the input field to the console.

Fill in the // ??? parts in the handleSubmit function to make it work.

import { useState } from 'react';

function SearchForm() {
  const [query, setQuery] = useState('');

  const handleSubmit = (event) => {
    // ??? 1: Prevent page reload
    
    // ??? 2: Log the value from the form's input element
    console.log('Searching for:', event.target.elements.searchInput.value);
  };

  const handleInputChange = (event) => {
    setQuery(event.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Search:
        <input 
          name="searchInput" 
          value={query} 
          onChange={handleInputChange} 
        />
      </label>
      <button type="submit">Search</button>
    </form>
  );
}
Show answer

The only line you need to add is event.preventDefault().

const handleSubmit = (event) => {
    // 1: Prevent page reload
    event.preventDefault(); 
    
    // 2: Log the value from the form's input element
    console.log('Searching for:', event.target.elements.searchInput.value);
};

The event.target in an onSubmit handler is the <form> element itself. You can then access its child input elements by their name attribute via the elements collection. Calling event.preventDefault() is the crucial step to stop the browser's default submission behavior.


Conclusion

You've now learned the fundamentals of making your React applications interactive. This is the foundation upon which all user input, from simple button clicks to complex forms, is built.

Key Takeaways:

  • Event handlers in React are attached via camelCased props like onClick.
  • You must pass a function reference (e.g., {myFunction}), not a function call (e.g., {myFunction()}), to event handler props.
  • React uses a SyntheticEvent system to provide a consistent, cross-browser event API.
  • This system uses performance optimizations like event delegation and event pooling.
  • The event.preventDefault() method is essential for controlling default browser behaviors, especially in forms.
  • The event handler has access to useful information through the event object, such as event.target.

In the next lesson, we will build directly on this foundation by exploring how to "Type React's synthetic events correctly in a TypeScript environment." You'll learn how to leverage TypeScript to make your event handlers more robust and self-documenting.