💻Lecture
Notes Of Class
6 Handling Events in React
🎯 Objective:
To
understand how to add interactivity to web pages using event handlers in
React (like onClick, onChange, and onSubmit) and apply them to control the
behavior of UI elements.
🧠 What are Events in React?
In
web development, events are actions or occurrences that happen in the
browser — such as a user clicking a button, typing in a text box, submitting a
form, etc.
React
uses event handlers
to let us respond to these actions and define what should happen when the user
interacts with elements.
📘 1. onClick Event
- Triggered when a user clicks
on an element (like a button).
- Used to perform actions such as
changing a value, toggling something, or showing a message.
✅ Example:
import React, { useState } from 'react';
function ClickExample() {
const [message, setMessage] = useState("Hello");
function handleClick() {
setMessage("You clicked the button!");
}
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
Explanation:
- useState creates a state
variable called message.
- handleClick() updates the
message when the button is clicked.
- The onClick attribute is
attached to the <button> element.
📘 2. onChange Event
- Triggered when a user types
or changes the value in an input field.
- Useful for tracking input data
in real-time.
✅ Example:
import React, { useState } from 'react';
function ChangeExample() {
const [name, setName] = useState("");
setName(event.target.value);
}
return (
<div>
<input type="text" onChange={handleChange} placeholder="Type
your name" />
<p>Your name is: {name}</p>
</div>
);
}
Explanation:
- event.target.value gets the
current input value.
- Every time the user types, onChange
updates the state.
📘 3. onSubmit Event
- Used when submitting a form.
- Allows us to prevent default
page reload and handle form logic ourselves.
✅ Example:
import React, { useState } from 'react';
function SubmitExample() {
const [email, setEmail] = useState("");
function handleSubmit(event) {
event.preventDefault(); // Prevents the page from reloading
alert(`Form submitted with email: ${email}`);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
placeholder="Enter your
email"
value={email}
onChange={(e) =>
setEmail(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
💡 Activity: Toggle Text with
a Button
🔧 Task:Create a button that toggles text between "Hello" and "Goodbye" when clicked.
✅ Example Code:
import React, { useState } from 'react';
function ToggleText() {
const [text, setText] = useState("Hello");
function toggleText() {
setText(prevText => prevText === "Hello" ? "Goodbye"
: "Hello");
}
return (
<div>
<p>{text}</p>
<button onClick={toggleText}>Toggle Text</button>
</div>
);
}
📝 Homework: Build a Toggle
Switch
💼 Task:Create a checkbox that acts like a toggle switch.
- When checked, display:
"Dark Mode On"
- When unchecked, display:
"Dark Mode Off"
✅ Hints:
- Use useState to store a boolean
value.
- Use the onChange event to
detect checkbox state.
💡 Sample Outline:
const [isDark, setIsDark] = useState(false);
function handleToggle(event) {
setIsDark(event.target.checked);
}
✅ Summary
|
Event |
Use Case |
Triggered When |
|
onClick |
Handle button clicks |
A button or element is clicked |
|
onChange |
Handle input changes |
A user types in a field |
|
onSubmit |
Handle form submission |
A form is submitted |
📚 Practice Questions
1.
What
does the onClick event do?
2.
How
do you prevent a form from reloading the page?
3.
What
is the difference between onChange and onSubmit?
1.
What does the onClick event do?
The onClick
event in React is used to handle click actions by the user, such as clicking a
button or a div.
When the user clicks the element, the function assigned to onClick
is executed.
Example:
<button onClick={handleClick}>Click Me</button>
In this case, when the button is clicked, the handleClick
function runs.
function handleClick() { alert("Button clicked!");}
2. How do you prevent a
form from reloading the page?
In React, forms try to submit and reload the
page by default.
To stop this, you use:
event.preventDefault();
inside the function that handles form submission.
Example:
function handleSubmit(event) { event.preventDefault(); // Prevents page reload // Handle form data here}<form onSubmit={handleSubmit}> <button type="submit">Submit</button></form>
3. What is the
difference between onChange and onSubmit?
|
Event |
Purpose |
Usage
Example |
|
|
Tracks changes to
input fields (text, etc.) |
Used in input
elements like |
|
|
Handles form
submission |
Used in |
onChange:
·
Fires
every time the input value changes.
·
Commonly
used to update state as the user types.
<input type="text" onChange={handleInputChange} />
onSubmit:
·
Fires
once when the user submits the form (usually by pressing Enter or clicking a
submit button).
·
Used
to collect and process all form data.
<form onSubmit={handleFormSubmit}> <button type="submit">Submit</button></form>
