Handling Events in React
Learn how to handle button clicks, input changes, form submissions, and other user actions using simple React event handlers.
1. What Is Event Handling?
Event handling means performing an action when a user interacts with an application. In React, we use event handler functions to respond to these actions.
For example, when a user clicks a button, we can display a message, update a counter, or open another section.
function HandlingEvents() {
function handleClick() {
alert("Button clicked successfully!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default HandlingEvents;
Explanation: When the user clicks the
button, React calls handleClick() and
displays an alert.
Clicking the button displays an alert message.
2. Handling Click Events
A click event occurs when a user clicks an element.
In React, the onClick prop handles this event.
function ClickEvent() {
function showMessage() {
console.log("Welcome to CIIT!");
}
return (
<button onClick={showMessage}>
Show Message
</button>
);
}
export default ClickEvent;
Simple Explanation: The function
showMessage runs only when the user clicks
the button.
3. Handling Events with State
We can use an event handler to update a component's state. When state changes, React updates the relevant UI.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(previousCount => previousCount + 1);
}
return (
<div>
<h3>Count: {count}</h3>
<button onClick={handleClick}>
Increase
</button>
</div>
);
}
export default Counter;
useState(0)starts the count at zero.handleClick()runs after the button is clicked.setCount()increases the count by one.- React displays the updated count.
Counter Demo
Click Increase to change the count.
4. Handling Input Change Events
The onChange event handles changes in an input
field. It is commonly used when users enter text or select
a value.
import { useState } from "react";
function NameInput() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<input
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
<p>Your name: {name}</p>
</div>
);
}
export default NameInput;
event.target.value gets the current input value.
setName() saves that value in React state.
5. Handling Form Submit Events
The onSubmit event handles form submission.
We commonly use event.preventDefault() to
stop the browser from reloading the page when a form is
submitted.
function StudentForm() {
function handleSubmit(event) {
event.preventDefault();
alert("Form submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter student name"
required
/>
<button type="submit">
Submit
</button>
</form>
);
}
export default StudentForm;
handleSubmit() handles the form submission.
preventDefault() prevents the browser's normal
form submission behavior.
6. Passing Arguments to Event Handlers
Sometimes we need to pass a value to an event handler. We can use an arrow function to pass that value when the event occurs.
function CourseButton() {
function showCourse(courseName) {
alert("Selected course: " + courseName);
}
return (
<button
onClick={() => showCourse("React Development")}>
View Course
</button>
);
}
export default CourseButton;
"React Development" to
showCourse().
Clicking the button displays: Selected course: React Development
7. Handling Keyboard Events
Keyboard events allow us to respond when a user presses a
key. The onKeyDown prop can handle key presses.
function KeyboardEvent() {
function handleKeyDown(event) {
if (event.key === "Enter") {
console.log("Enter key pressed!");
}
}
return (
<input
type="text"
onKeyDown={handleKeyDown}
placeholder="Press Enter"
/>
);
}
export default KeyboardEvent;
8. Common Mistakes
1. Calling the handler immediately
// Incorrect for ordinary click handling
<button onClick={handleClick()}>
Click
</button>
// Correct
<button onClick={handleClick}>
Click
</button>
Pass the function reference when it should run after the click.
2. Forgetting preventDefault in a form
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
Use preventDefault() when you want to prevent
the browser's default form submission behavior.
3. Using the wrong event prop
// Correct for input changes
<input onChange={handleChange} />
// Correct for button clicks
<button onClick={handleClick}>
Click
</button>
Select the event prop that matches the user action.
9. Practice Questions
- What is event handling in React?
- How do you handle a button click in React?
- How can you update state inside an event handler?
- What is the purpose of
onChange? - Why do we use
event.preventDefault()in forms? - How do you pass an argument to an event handler?
- Write a component that displays a message when Enter is pressed.
- Write a form that displays a success message after submission.
Summary
Event handling allows React components to respond to user actions.
Use onClick for clicks, onChange for input
changes, onSubmit for forms, and onKeyDown
for keyboard input. Event handlers can update state, access event
information, and receive arguments. Use preventDefault()
when you need to stop the browser's default behavior.