Event Handling in React
# 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> ); }
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> ); }
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..." /> ); }
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> ); }
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.