Skip to main content
React Introduction
CHAPTER 08 Beginner

Event Handling in React

Updated: May 13, 2026
15 min read

# Event Handling in React

1. Introduction

A static webpage is boring. Modern web applications require constant user interaction: clicking buttons, hovering over images, typing in search boxes, and submitting forms. In React, handling these interactions is very similar to standard HTML, but with a few crucial syntactic differences. In this chapter, we will learn how to handle events the React way.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Attach event listeners (like onClick, onChange, onSubmit) to JSX elements.
  • Understand React's camelCase event naming convention.
  • Pass functions as event handlers.
  • Access the synthetic event object (e).
  • Prevent default browser behaviors during form submissions.

3. Beginner-Friendly Explanations

How Events Work in HTML vs. React

In traditional HTML, event attributes are completely lowercase, and you pass a string of JavaScript to them: <button onclick="submitForm()">Click Me</button>

In React, event attributes use camelCase, and you pass a function reference inside curly braces: <button onClick={submitForm}>Click Me</button>

Notice there are no parentheses () after submitForm. If you put parentheses, the function runs immediately when the page loads, instead of waiting for the click!

4. Syntax Explanation

Click Events (onClick)

The most common event. Used for buttons, links, and divs.

```jsx id="ch8_ex1" // Example React component function ClickDemo() { const handleClick = () => { alert("Button was clicked!"); };

return ( // Correct: Pass the function name without () <button onClick={handleClick}>Click Me</button> ); }

123
### Passing Arguments to Event Handlers
What if you need to pass an argument to the function? (e.g., clicking "Delete" on an item with ID 5). You cannot write `onClick={deleteItem(5)}` because that runs immediately. Instead, wrap it in an inline arrow function:

jsx id="ch8_ex2" // Example React component function ItemList() { const deleteItem = (id) => { alert(Deleting item ${id}); };

return ( // Wrap in an arrow function to delay execution until clicked! <button onClick={() => deleteItem(5)}>Delete Item 5</button> ); }

123
### The Event Object (`e`)
Whenever an event occurs, React automatically passes an "Event Object" to your handler. This object contains data about the event (what was clicked, what was typed, etc.).

jsx id="ch8_ex3" // Example React component function InputDemo() { const handleType = (e) => { // e.target.value contains the text the user just typed! console.log(e.target.value); };

return ( <input type="text" onChange={handleType} placeholder="Type here..." /> ); }

123456789101112
## 5. Output Explanations
In `InputDemo`, every single time a user presses a key inside the text box, the `onChange` event fires. It calls `handleType` and passes the event object `e`. We then look inside `e.target` (the input element itself) and grab its `value` (the text), logging it to the console.

## 6. Real-World Examples
- **`onClick`**: Expanding a mobile hamburger menu, submitting a payment, or toggling dark mode.
- **`onChange`**: Live-validating an email address format as the user types it in.
- **`onSubmit`**: Sending a completed login form to a server.
- **`onMouseEnter` / `onMouseLeave`**: Showing a tooltip when a user hovers over an info icon.

## 7. Form Submission (`onSubmit`)
Forms naturally want to refresh the entire webpage when submitted. In React SPAs, we don't want the page to refresh! We use `e.preventDefault()` to stop this.

jsx id="ch8_ex4" // Example React component function SimpleForm() { const handleSubmit = (e) => { e.preventDefault(); // STOPS the page from refreshing! alert("Form submitted via React!"); };

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

123456789101112131415
## 8. Common Mistakes
- **Calling the function instead of passing it:** `onClick={myFunction()}` instead of `onClick={myFunction}`. This is the #1 mistake beginners make with events.
- **Lowercase event names:** Writing `onclick` instead of `onClick`. React will warn you in the console that `onclick` is not a valid attribute.

## 9. Best Practices
- Name your handler functions starting with `handle` (e.g., `handleClick`, `handleSubmit`, `handleInputChange`).
- Name your props that accept functions starting with `on` (e.g., `onClose`, `onSubmit`).

## 10. Exercises
1. Create a button that logs "Hovered!" to the console when the mouse enters the button area using `onMouseEnter`.
2. Create an input field that updates a state variable using `onChange` and `e.target.value`.

## 11. Mini Project: Interactive Profile Card
Let's combine `useState` and multiple event handlers to create a highly interactive profile card.

jsx id="ch8_proj1" // Example React component import React, { useState } from 'react';

export default function InteractiveProfile() { const [isFollowing, setIsFollowing] = useState(false); const [hoverColor, setHoverColor] = useState('border-gray-200');

const handleFollowClick = () => { setIsFollowing(!isFollowing); // Toggle the state };

return ( <div className="min-h-screen flex items-center justify-center bg-slate-50"> <div // Mouse enter event onMouseEnter={() => setHoverColor('border-blue-400')} // Mouse leave event onMouseLeave={() => setHoverColor('border-gray-200')} className={bg-white p-8 rounded-2xl shadow-lg border-2 ${hoverColor} transition-colors duration-300 text-center max-w-sm w-full} > <img src="https://i.pravatar.cc/150?img=32" alt="Profile" className="w-24 h-24 rounded-full mx-auto mb-4 border-4 border-slate-100" /> <h2 className="text-2xl font-bold text-slate-800">David Chen</h2> <p className="text-slate-500 mb-6">Full Stack Developer</p> <button // Click event onClick={handleFollowClick} className={w-full py-3 rounded-lg font-bold transition ${ isFollowing ? 'bg-slate-100 text-slate-800 hover:bg-slate-200' : 'bg-blue-600 text-white hover:bg-blue-700' }} > {isFollowing ? 'Following' : 'Follow'} </button> </div> </div> ); } ``

12. Coding Challenges

Challenge 1: Create an application with a single state variable
bgColor. Add three buttons: "Red", "Green", "Blue". When a user clicks a button, change the bgColor state, and apply that color to the background of the main <div>.

13. MCQs with Answers

Q1: What is the correct syntax for an onClick handler in React? A)
onclick="doSomething()" B) onClick={doSomething} C) onclick={doSomething()} D) onClick="doSomething" *Answer: B*

Q2: How do you prevent a form from causing a full page reload upon submission? A) By returning false from the component. B) By wrapping the form in a Fragment. C) By calling e.preventDefault() inside the onSubmit handler. D) React automatically prevents this by default. *Answer: C*

14. Interview Questions

  • Q: How are events handled differently in React compared to vanilla HTML/JS?
  • Q: What is the e object passed to event handlers in React? *(Answer: It is a SyntheticEvent, a cross-browser wrapper around the browser's native event).*

15. FAQs

Can I have multiple event handlers on a single element? Yes! An input can have an
onChange, an onFocus, and an onBlur all at the same time.

16. Summary

Handling user interactions is critical for building web apps. By utilizing camelCase event attributes (
onClick, onChange) and passing functional references (rather than invoking them immediately), you can easily execute logic and trigger state updates based on user actions.

17. Next Chapter Recommendation

Our interactive profile card used a ternary operator
{isFollowing ? 'Following' : 'Follow'}` to change the button text. This is a sneak peek at our next topic! In Chapter 9: Conditional Rendering in React, we will learn how to show, hide, and alter UI components based on logic and state.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·