Event Handling
Handling Events in React
React provides an event system that is similar to native DOM events, but it uses camelCase syntax and accepts JavaScript functions as handlers.
onClick
function GreetingButton() {
const greet = () => {
alert("Hello! Welcome to React!");
};
return <button onClick={greet}>Greet Me</button>;
}
onChange
onChange is used to detect changes on an input.
import { useState } from 'react';
function NameInput() {
const [name, setName] = useState("");
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<p>Hello, {name}!</p>
</div>
);
}
onSubmit
onSubmit is used on a form to handle data submission.
import { useState } from 'react';
function FormLogin() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
console.log("Email:", email);
console.log("Password:", password);
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Log In</button>
</form>
);
}
Preventing Default Behavior
Some events have a default behavior that needs to be prevented, such as a form reloading the page.
function CommentForm() {
const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
// Process the form data here
};
return (
<form onSubmit={handleSubmit}>
<textarea placeholder="Write a comment..." />
<button type="submit">Send</button>
</form>
);
}
Passing Arguments to Event Handlers
function ShoppingList() {
const [items, setItems] = useState(["Apple", "Mango", "Orange"]);
const removeItem = (index) => {
setItems(items.filter((_, i) => i !== index));
};
return (
<ul>
{items.map((item, index) => (
<li key={index}>
{item}
<button onClick={() => removeItem(index)}>Delete</button>
</li>
))}
</ul>
);
}
Use an arrow function () => removeItem(index) so the argument is only sent when the event fires.
Synthetic Events
React uses Synthetic Events that wrap native DOM events. This ensures consistency across browsers.
function ExampleEvent(e) {
// e is a SyntheticEvent
console.log("Event type:", e.type);
console.log("Target:", e.target);
// Access the native event if needed
console.log("Native event:", e.nativeEvent);
}
Complete Example: Form Input Handling
import { useState } from 'react';
function MessageForm() {
const [form, setForm] = useState({ name: "", message: "" });
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Message from ${form.name}: ${form.message}`);
setForm({ name: "", message: "" });
};
return (
<form onSubmit={handleSubmit}>
<input
name="name"
value={form.name}
onChange={handleChange}
placeholder="Name"
/>
<textarea
name="message"
value={form.message}
onChange={handleChange}
placeholder="Message"
/>
<button type="submit">Send</button>
</form>
);
}
export default MessageForm;
Summary
Event handling in React is similar to native DOM events but with a few syntax differences. Always use e.preventDefault() to prevent unwanted default behavior, and use arrow functions to pass arguments to handlers.
The next chapter covers Conditional Rendering — how to display UI elements conditionally based on specific data.