Handling Click Events in React JS
Course: React JS Training
Topic: Handling Click Events
Official Documentation: React – Responding to Events
1. Introduction to Handling Click Events
Handling click events is an essential concept in React JS that allows developers to make web applications interactive. A click event occurs when a user clicks an element such as a button, link, icon, or other interactive control.
React provides the onClick event handler to execute a function when a user clicks an element. Developers commonly use click events to update state, submit forms, open menus, delete items, increase counters, display messages, and perform other actions.
For example, when a user clicks an Increase button, a counter can increase by one. When a user clicks a Delete button, an item can be removed from a list.
2. What Is an Event in React JS?
An event is an action or occurrence that happens in the browser, usually as a result of user interaction. React allows components to respond to events through event handler functions.
Common events in React include:
onClick – Occurs when an element is clicked.
onChange – Occurs when an input value changes.
onSubmit – Occurs when a form is submitted.
onMouseEnter – Occurs when the pointer enters an element.
onMouseLeave – Occurs when the pointer leaves an element.
onKeyDown – Occurs when a key is pressed down.
onFocus – Occurs when an element receives focus.
onBlur – Occurs when an element loses focus.
In React JSX, event handler names use camelCase, such as onClick, rather than lowercase HTML-style event attributes such as onclick.
3. What Is the onClick Event Handler?
The onClick event handler is a React prop that accepts a function. React calls that function when the associated element receives a click event.
Syntax:
<button onClick={handleClick}>
Click Me
</button>
In this example, handleClick is a function that React calls when the button is clicked. The function is passed without parentheses because it should execute in response to the click, not during rendering.
4. Creating a Simple Click Event
The simplest way to handle a click event is to define a function inside a component and pass it to the element's onClick prop.
Example:
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<div>
<h2>React Click Event</h2>
<button onClick={handleClick}>
Click Me
</button>
</div>
);
}
export default App;
Explanation:
- The
handleClick() function is defined inside the component.
- The button receives the function through the
onClick prop.
- When the user clicks the button, React invokes the function.
- The browser displays an alert message.
5. Understanding Event Handler Functions
An event handler is a function that runs in response to a particular event. In React, event handlers are commonly named using the word handle followed by the event name or action.
Examples of Event Handler Names:
function handleClick() {
console.log("Button clicked");
}
function handleDelete() {
console.log("Delete action");
}
function handleSubmit() {
console.log("Form submitted");
}
Using descriptive names makes the code easier to understand and maintain.
6. Passing a Function vs. Calling a Function
One of the most common mistakes beginners make is calling an event handler directly instead of passing the function to the event handler prop.
Correct Approach:
<button onClick={handleClick}>
Click Me
</button>
Incorrect Approach:
<button onClick={handleClick()}>
Click Me
</button>
Explanation: In the correct approach, React receives the function and executes it when the button is clicked. In the incorrect approach, JavaScript calls the function while rendering the component, which may cause the action to run too early.
If you need to pass arguments to a handler, use an arrow function:
<button onClick={() => handleClick("React")}>
Click Me
</button>
7. Handling Click Events with Arrow Functions
Arrow functions provide a concise way to define event handlers directly inside JSX. They are particularly useful when a function needs to receive arguments.
Example:
function App() {
function showMessage(name) {
alert("Hello, " + name);
}
return (
<div>
<button onClick={() => showMessage("Rahul")}>
Say Hello
</button>
</div>
);
}
export default App;
When the button is clicked, the arrow function calls showMessage() with the value Rahul.
8. Handling Click Events with State
Click events are frequently used to update state. React's useState() Hook allows a component to remember information and display updated values after a user interaction.
Example: Counter Application
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(previousCount => previousCount + 1);
}
return (
<div>
<h2>Count: {count}</h2>
<button onClick={handleClick}>
Increase Count
</button>
</div>
);
}
export default Counter;
Explanation:
- The initial count is zero.
- The button uses the
onClick event handler.
- Each click calls
handleClick().
- The state setter increases the previous count by one.
- React renders the updated count.
9. Handling Multiple Click Events
A component can contain multiple buttons, each with its own event handler. Different handlers can perform different actions based on the user's selection.
Example:
function App() {
function handleSave() {
alert("Data saved successfully!");
}
function handleDelete() {
alert("Data deleted successfully!");
}
function handleCancel() {
alert("Operation cancelled!");
}
return (
<div>
<button onClick={handleSave}>Save</button>
<button onClick={handleDelete}>Delete</button>
<button onClick={handleCancel}>Cancel</button>
</div>
);
}
export default App;
Each button invokes its corresponding handler when clicked. This approach helps separate application actions into clear and reusable functions.
10. Passing Arguments to Click Event Handlers
Sometimes, an event handler needs additional information, such as a product ID, user name, or task ID. You can pass these arguments using an arrow function.
Example:
function App() {
function showProduct(productName) {
alert("Selected product: " + productName);
}
return (
<div>
<button onClick={() => showProduct("Laptop")}>
Laptop
</button>
<button onClick={() => showProduct("Mobile")}>
Mobile
</button>
</div>
);
}
export default App;
When the Laptop button is clicked, the handler receives Laptop. When the Mobile button is clicked, it receives Mobile.
11. Accessing the Event Object
React passes an event object to the event handler when the event occurs. This object provides information about the event, including the target element and methods for controlling event behavior.
Example:
function App() {
function handleClick(event) {
console.log("Event type:", event.type);
console.log("Clicked element:", event.currentTarget);
}
return (
<button onClick={handleClick}>
Inspect Click
</button>
);
}
export default App;
Explanation:
event.type identifies the event type, such as click.
event.target refers to the element where the event originated.
event.currentTarget refers to the element whose handler is currently executing.
The event object is useful when handling interactions with nested elements or when you need details about the element that triggered an event.
12. Event Bubbling in React
Event bubbling occurs when an event triggered on a child element propagates upward through its parent elements. As a result, both the child and parent event handlers may run when the child is clicked.
Example:
function App() {
function handleParentClick() {
console.log("Parent clicked");
}
function handleChildClick() {
console.log("Child clicked");
}
return (
<div onClick={handleParentClick}>
<button onClick={handleChildClick}>
Click Child
</button>
</div>
);
}
export default App;
Output when the button is clicked:
Child clicked
Parent clicked
The child's click handler runs first, followed by the parent's click handler, because the click event bubbles upward.
13. Stopping Event Propagation
Sometimes, you want a child element's click event to run without triggering the parent element's click handler. React allows you to stop event propagation by calling event.stopPropagation().
Example:
function App() {
function handleParentClick() {
console.log("Parent clicked");
}
function handleChildClick(event) {
event.stopPropagation();
console.log("Child clicked");
}
return (
<div onClick={handleParentClick}>
<button onClick={handleChildClick}>
Click Child
</button>
</div>
);
}
export default App;
Output:
Child clicked
The parent handler does not run for this click because propagation has been stopped.
14. Preventing Default Browser Behavior
Some browser events have a default action. For example, submitting a form may cause the browser to navigate or reload the page. In React, event.preventDefault() can prevent the default browser behavior.
Example:
function App() {
function handleSubmit(event) {
event.preventDefault();
alert("Form submitted without page reload!");
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>
);
}
export default App;
In this example, the form submission is handled by React without the browser performing its normal submission navigation.
Important Difference:
event.preventDefault() prevents the default browser action.
event.stopPropagation() prevents the event from bubbling to ancestor handlers.
15. Handling Click Events in Custom Components
React components can receive event handler functions through props. This allows a parent component to decide what happens when a button inside a reusable child component is clicked.
Example:
function CustomButton({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
function App() {
function handleClick() {
alert("Custom button clicked!");
}
return (
<div>
<CustomButton onClick={handleClick}>
Click Here
</CustomButton>
</div>
);
}
export default App;
The CustomButton component is reusable because it accepts its click behavior through the onClick prop instead of defining a fixed action internally.
16. Handling Click Events for Show and Hide Functionality
Click events can control whether specific content is displayed. This pattern is commonly used for dropdown menus, FAQs, additional information, and expandable sections.
Example:
import { useState } from "react";
function App() {
const [isVisible, setIsVisible] = useState(false);
function handleToggle() {
setIsVisible(previousValue => !previousValue);
}
return (
<div>
<button onClick={handleToggle}>
{isVisible ? "Hide Details" : "Show Details"}
</button>
{isVisible && (
<p>This is additional information displayed on click.</p>
)}
</div>
);
}
export default App;
Initially, the details are hidden. Clicking the button changes the state and displays the paragraph. Clicking again hides it.
17. Handling Click Events for Delete Operations
Click events can also remove items from a list. When working with React state arrays, use a non-mutating method such as filter() to create the updated array.
Example:
import { useState } from "react";
function App() {
const [items, setItems] = useState([
{ id: 1, name: "Laptop" },
{ id: 2, name: "Mobile" },
{ id: 3, name: "Keyboard" }
]);
function handleDelete(itemId) {
setItems(previousItems =>
previousItems.filter(item => item.id !== itemId)
);
}
return (
<div>
<h2>Product List</h2>
{items.map(item => (
<div key={item.id}>
<span>{item.name}</span>
<button onClick={() => handleDelete(item.id)}>
Delete
</button>
</div>
))}
</div>
);
}
export default App;
Each Delete button passes the selected item's ID to the handler. The filter() method creates a new array without the selected item.
18. Common Mistakes When Handling Click Events
- Calling the handler during rendering: Avoid writing
onClick={handleClick()} when you intend to run the function on click.
- Incorrect event prop capitalization: Use
onClick, not onclick, in JSX.
- Forgetting to pass a function: The event handler prop should receive a function reference or a function expression.
- Passing arguments incorrectly: Use
onClick={() => handleClick(id)} when the handler needs an argument.
- Mutating state directly: Use a state setter and create a new array or object when changing state.
- Ignoring event propagation: Understand that clicks on nested elements can trigger ancestor handlers.
- Confusing preventDefault and stopPropagation: These methods serve different purposes.
- Using non-semantic clickable elements: Prefer a real
<button> for button actions because it supports keyboard interaction and accessibility features.
- Using alert for every action: In real applications, update the interface or perform the required operation instead of relying on alerts for all feedback.
19. Practical Project: Interactive Counter and Message App
Objective: Create a React application that increases and decreases a counter, resets the count, and displays a message when a button is clicked.
Complete Code:
import { useState } from "react";
function ClickEventProject() {
const [count, setCount] = useState(0);
const [message, setMessage] = useState("Click a button to begin");
function handleIncrease() {
setCount(previousCount => previousCount + 1);
setMessage("Counter increased!");
}
function handleDecrease() {
setCount(previousCount => previousCount - 1);
setMessage("Counter decreased!");
}
function handleReset() {
setCount(0);
setMessage("Counter reset!");
}
return (
<div>
<h2>React Click Event Project</h2>
<h3>Count: {count}</h3>
<button onClick={handleIncrease}>Increase</button>
<button onClick={handleDecrease}>Decrease</button>
<button onClick={handleReset}>Reset</button>
<p>{message}</p>
</div>
);
}
export default ClickEventProject;
Project Explanation:
- The
count state stores the current counter value.
- The
message state stores feedback for the user.
- The Increase button increments the counter.
- The Decrease button decrements the counter.
- The Reset button sets the counter back to zero.
- Each handler updates the message to describe the action performed.
- React renders the new counter value and message after the state updates.
20. Best Practices for Handling Click Events
- Use the
onClick prop to register click handlers in JSX.
- Keep event handlers descriptive and focused on a specific action.
- Pass function references rather than calling functions during rendering.
- Use arrow functions when passing arguments to handlers.
- Use state setters to update data that affects the interface.
- Use functional state updates when the next state depends on the previous state.
- Use
event.stopPropagation() only when parent handlers should not receive the click.
- Use
event.preventDefault() when you need to prevent a browser's default action.
- Prefer semantic HTML elements, such as buttons, for clickable controls.
- Keep reusable components flexible by accepting event handler props.
- Test clicks with mouse, keyboard, and assistive technology where appropriate.
21. Interview Questions and Answers
Q1. What is click event handling in React?
Answer: Click event handling allows a React component to execute a function when a user clicks an element. The onClick prop is commonly used for this purpose.
Q2. What is the onClick event handler?
Answer: onClick is a React prop that receives a function to execute when the associated element is clicked.
Q3. What is the difference between onClick={handleClick} and onClick={handleClick()}?
Answer: The first passes the function to React for execution on click. The second calls the function immediately during rendering.
Q4. How can you pass arguments to a click handler?
Answer: Use an arrow function, such as onClick={() => handleClick(id)}.
Q5. What is event bubbling?
Answer: Event bubbling is the process by which an event propagates from the target element upward through its ancestor elements.
Q6. What does event.stopPropagation() do?
Answer: It prevents an event from propagating to ancestor event handlers.
Q7. What does event.preventDefault() do?
Answer: It prevents the default browser behavior associated with an event, such as the normal navigation caused by a form submission.
Q8. How are click events used with state?
Answer: Click handlers can call state setter functions to update values, such as counters, visibility flags, or items in a list.
Q9. Can a custom React component accept an onClick prop?
Answer: Yes. A custom component can accept an event handler function through props and pass it to a built-in element such as a button.
Q10. Why should we use a button instead of a clickable div?
Answer: A semantic button provides built-in keyboard interaction and accessibility behavior, making it more appropriate for actions.
22. Practice Exercises
- Create a button that displays an alert message when clicked.
- Build a counter with Increase, Decrease, and Reset buttons.
- Create a Show Details button that toggles paragraph visibility.
- Build a product list with a Delete button for every item.
- Create two buttons that display different messages.
- Build a parent container with a child button and test event bubbling.
- Prevent a child click from triggering the parent click handler.
- Create a form that handles submission without reloading the page.
- Build a reusable custom button component that accepts an onClick prop.
- Create a simple task list with click-based completion controls.
23. Quick Revision Checklist
- Understand events and event handlers in React.
- Know how to use the
onClick prop.
- Pass functions instead of calling them during rendering.
- Use arrow functions to pass arguments.
- Access the event object when necessary.
- Understand event bubbling and propagation.
- Know the difference between
stopPropagation() and preventDefault().
- Update component state through state setter functions.
- Pass event handlers through props to reusable components.
- Use semantic and accessible interactive elements.
24. Conclusion
Handling click events is a fundamental React JS skill for creating interactive web applications. By using onClick, event handler functions, arrow functions, and state updates, developers can respond to user actions and update the interface dynamically.
Understanding event propagation, preventing default browser behavior, passing arguments, and building reusable components helps you write cleaner and more maintainable React applications. These concepts are widely used in counters, forms, shopping carts, task managers, menus, and dashboards.
25. React JS Training and Course Demo
Learn more about React JS, event handling, component development, and practical application building through JustAcademy.
Course Link: JustAcademy React JS Training
Demo Registration: Register for React JS Course Demo