Event Handling with Functions in React JS
Event Handling with Functions in React JS is the process of defining JavaScript functions and connecting them to user interactions such as clicking buttons, typing into input fields, submitting forms, hovering over elements, and selecting options. React uses event handler props such as onClick, onChange, onSubmit, and onMouseEnter to execute functions when specific events occur.
Event handling is an essential React concept because it makes applications interactive. By using functions as event handlers, developers can update state, display messages, validate forms, select products, delete items, and respond to user actions.
1. What Is Event Handling in React?
Event handling is the process of responding to an action performed by a user or browser. In React, you define a function and pass it to an appropriate event prop in JSX. React calls that function when the event occurs.
Example
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default App;
Explanation
App() is a React function component.
handleClick() is a JavaScript function that handles the click event.
onClick is the React event prop used for click interactions.
onClick={handleClick} passes the function to the button.
- When the user clicks the button, React executes the function and displays an alert.
2. What Is an Event Handler Function?
An event handler function is a function that contains the logic to execute when a particular event occurs. Event handlers are commonly named using the word handle followed by the event or action name.
Common Naming Conventions
| Function Name |
Purpose |
handleClick() |
Handles a click event. |
handleChange() |
Handles a form field change. |
handleSubmit() |
Handles form submission. |
handleMouseEnter() |
Handles the pointer entering an element. |
handleFocus() |
Handles an element receiving focus. |
handleDelete() |
Handles a delete action. |
handleSave() |
Handles a save action. |
These names are conventions, not mandatory JavaScript rules. Clear function names help developers understand what each handler does.
3. Using the onClick Event with a Function
The onClick event is used when a user clicks an element, such as a button. It is one of the most commonly used event handlers in React applications.
Example: Displaying a Message
function MessageButton() {
function showMessage() {
alert("Welcome to React JS!");
}
return (
<div>
<h2>React Event Handling</h2>
<button onClick={showMessage}>
Show Message
</button>
</div>
);
}
export default MessageButton;
How It Works
- The component defines a function named
showMessage.
- The button receives that function through
onClick.
- The user clicks the button.
- React executes
showMessage().
- The browser displays the message.
4. Passing a Function Versus Calling a Function
One of the most important rules in React event handling is that you normally pass a function reference to an event prop instead of calling the function during rendering.
| Syntax |
Meaning |
onClick={handleClick} |
Correct: passes the function to React to execute when clicked. |
onClick={() => handleClick()} |
Correct: passes an arrow function that calls the handler when clicked. |
onClick={handleClick()} |
Usually incorrect: calls the function during rendering. |
onClick={() => alert("Hello")} |
Correct: creates an inline function that runs after the click. |
Incorrect Example
function App() {
function handleClick() {
alert("Clicked!");
}
return (
<button onClick={handleClick()}>
Click Me
</button>
);
}
Problem: The function is called while React renders the component rather than being passed as the click handler. This can cause unwanted behavior.
Correct Example
function App() {
function handleClick() {
alert("Clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default App;
5. Defining Event Handler Functions Inside Components
Event handler functions are often defined inside a React component because they may need access to that component's props and state.
Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleIncrement() {
setCount((previousCount) => previousCount + 1);
}
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={handleIncrement}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation
useState(0) initializes the counter with a value of zero.
handleIncrement() defines the click behavior.
setCount() updates the component's state.
- The functional updater receives the previous state and returns the new value.
- React renders the updated counter after the state changes.
6. Using Arrow Functions for Event Handling
Arrow functions provide a concise way to define event handlers directly in JSX. They are especially useful when a handler needs arguments or when the action is short.
Example
function App() {
return (
<div>
<button onClick={() => alert("Login clicked")}>
Login
</button>
<button onClick={() => alert("Register clicked")}>
Register
</button>
</div>
);
}
export default App;
Advantages
- Provides concise syntax for short event handlers.
- Makes it easy to pass arguments to functions.
- Allows small pieces of event logic to be written near the JSX element.
- Can be used to call a named function after an event occurs.
For longer or more complex logic, defining a separate named handler function often improves readability.
7. Handling Events with Arguments
Sometimes an event handler needs additional information, such as a user ID, product ID, item name, or selected value. An arrow function can pass those arguments to the handler when the event occurs.
Example
function App() {
function greetUser(name) {
alert("Hello, " + name);
}
return (
<div>
<button onClick={() => greetUser("Rahul")}>
Greet Rahul
</button>
<button onClick={() => greetUser("Priya")}>
Greet Priya
</button>
</div>
);
}
export default App;
Both buttons use the same function but pass different arguments. This makes the handler reusable.
8. Handling Events with the Event Object
React provides an event object to an event handler when the event occurs. It contains information about the event and the element involved. It is useful for reading input values, identifying event types, and controlling browser behavior.
Example
function App() {
function handleClick(event) {
console.log("Event type:", event.type);
console.log("Current target:", event.currentTarget);
}
return (
<button onClick={handleClick}>
Inspect Event
</button>
);
}
export default App;
Important Event Properties and Methods
| Property or Method |
Purpose |
event.type |
Returns the event type, such as click. |
event.target |
Identifies the element where the event originated. |
event.currentTarget |
Identifies the element whose handler is currently executing. |
event.preventDefault() |
Prevents the event's default browser action. |
event.stopPropagation() |
Stops the event from propagating to ancestor handlers. |
9. Handling Input Events with Functions
React uses the onChange event to respond to changes in form fields. A handler can read the input value and update component state.
Example
import { useState } from "react";
function NameInput() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="name">Enter your name:</label>
<input
id="name"
value={name}
onChange={handleChange}
placeholder="Your name"
/>
<p>Hello, {name || "Guest"}!</p>
</div>
);
}
export default NameInput;
Explanation
- The input is controlled by React state.
handleChange() runs whenever the input value changes.
event.target.value retrieves the current value.
setName() updates the state.
- The displayed greeting changes as the user types.
10. Handling Form Submission with Functions
The onSubmit event allows a function to process a form when the user submits it. It is commonly used for login, registration, feedback, and contact forms.
Example
function ContactForm() {
function handleSubmit(event) {
event.preventDefault();
alert("Form submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input id="email" type="email" required />
<button type="submit">Submit</button>
</form>
);
}
export default ContactForm;
event.preventDefault() prevents the browser's normal form submission navigation so the handler can process the submission. This example displays a message; a real application would also validate and send the data to an appropriate backend.
11. Passing Event Handler Functions as Props
React allows a parent component to pass an event handler function to a child component through props. This helps separate application logic from reusable UI elements.
Example
function CustomButton({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
function App() {
function handlePlay() {
alert("Playing video!");
}
function handleUpload() {
alert("Uploading file!");
}
return (
<div>
<CustomButton onClick={handlePlay}>
Play Video
</CustomButton>
<CustomButton onClick={handleUpload}>
Upload File
</CustomButton>
</div>
);
}
export default App;
Explanation
App defines two different event handler functions.
- The parent passes the functions to
CustomButton using the onClick prop.
CustomButton receives the function and attaches it to the HTML button.
- The same component can be reused for different actions.
12. Custom Event Handler Props
When creating your own components, you can use descriptive prop names such as onSave, onDelete, or onPlay. These are custom component props, not built-in browser event names.
Example
function SaveButton({ onSave }) {
return (
<button onClick={onSave}>
Save Changes
</button>
);
}
function App() {
function handleSave() {
alert("Changes saved!");
}
return <SaveButton onSave={handleSave} />;
}
export default App;
The SaveButton component receives the function through onSave and connects it to the built-in button's onClick event.
13. Event Handling with Conditional Rendering
Event handlers can update state to control which content appears on the screen. This is useful for showing or hiding details, opening menus, displaying messages, and toggling panels.
Example: Show and Hide Content
import { useState } from "react";
function ToggleContent() {
const [isVisible, setIsVisible] = useState(false);
function handleToggle() {
setIsVisible((previousValue) => !previousValue);
}
return (
<div>
<button onClick={handleToggle}>
{isVisible ? "Hide Details" : "Show Details"}
</button>
{isVisible && (
<p>This content is displayed conditionally.</p>
)}
</div>
);
}
export default ToggleContent;
Every click reverses the boolean state. React then updates the button text and conditionally displays the paragraph.
14. Updating State from Event Handler Functions
Event handlers commonly update React state in response to user interactions. When state changes, React re-renders the component so the interface reflects the new state.
Example: Like Button
import { useState } from "react";
function LikeButton() {
const [likes, setLikes] = useState(0);
function handleLike() {
setLikes((previousLikes) => previousLikes + 1);
}
return (
<div>
<p>Likes: {likes}</p>
<button onClick={handleLike}>
Like
</button>
</div>
);
}
export default LikeButton;
The handler uses a functional state update, which is helpful when the next value depends on the previous value. Avoid modifying state variables directly.
15. Event Bubbling and Function Handlers
Event bubbling means that an event triggered on a child element can propagate upward to its parent elements. If both a button and its parent have click handlers, clicking the button can run both handlers.
Example
function App() {
function handleParentClick() {
console.log("Parent clicked");
}
function handleButtonClick() {
console.log("Button clicked");
}
return (
<div onClick={handleParentClick}>
<button onClick={handleButtonClick}>
Click Me
</button>
</div>
);
}
export default App;
Clicking the button runs its click handler first and then the parent's click handler because the event bubbles upward.
Stopping Event Propagation
function App() {
function handleParentClick() {
console.log("Parent clicked");
}
function handleButtonClick(event) {
event.stopPropagation();
console.log("Button clicked");
}
return (
<div onClick={handleParentClick}>
<button onClick={handleButtonClick}>
Click Me
</button>
</div>
);
}
Calling event.stopPropagation() prevents the click event from reaching the parent handler. Use it only when stopping propagation is appropriate for the intended interaction.
16. Preventing Default Browser Behaviour
Some browser events have default actions. For example, submitting a traditional HTML form can navigate or reload the page. The event.preventDefault() method prevents the default action when your application needs to handle the event itself.
Example
function handleSubmit(event) {
event.preventDefault();
console.log("React handled the form submission.");
}
Difference: preventDefault() prevents the browser's default action, while stopPropagation() prevents the event from continuing to ancestor handlers. They serve different purposes.
17. Handling Events in Lists
In list-based interfaces, each item can have its own event handler. Passing the item ID lets the function identify which item the user selected.
Example: Delete a List Item
import { useState } from "react";
function ItemList() {
const [items, setItems] = useState([
{ id: 1, name: "HTML" },
{ id: 2, name: "CSS" },
{ id: 3, name: "React" }
]);
function handleDelete(itemId) {
setItems((previousItems) =>
previousItems.filter((item) => item.id !== itemId)
);
}
return (
<div>
{items.map((item) => (
<div key={item.id}>
<span>{item.name}</span>
<button onClick={() => handleDelete(item.id)}>
Delete
</button>
</div>
))}
</div>
);
}
export default ItemList;
Each button calls the same function with a different ID. The state update removes only the selected item and React renders the updated list.
18. Common Mistakes in Event Handling
| Mistake |
Why It Is Incorrect |
Correct Approach |
| Calling a handler in JSX |
onClick={handleClick()} executes during rendering. |
Use onClick={handleClick}. |
| Forgetting the event prop |
A function is defined but is not connected to the element. |
Use the appropriate event prop, such as onClick. |
| Writing complex inline logic |
It can make JSX difficult to read and maintain. |
Move complex logic into a named function. |
| Changing state directly |
Direct mutation does not correctly follow React's state update model. |
Use state setters and create updated values. |
| Using the wrong event prop |
The handler may not respond to the intended interaction. |
Choose an appropriate prop such as onChange or onSubmit. |
| Ignoring event bubbling |
Parent handlers may also run after a child interaction. |
Understand propagation and use stopPropagation() when necessary. |
| Using clickable non-interactive elements unnecessarily |
Keyboard accessibility may be reduced. |
Use semantic elements such as button for button actions. |
19. Best Practices for Event Handling with Functions
- Use descriptive function names such as
handleClick, handleSubmit, and handleDelete.
- Pass function references rather than calling event handlers during rendering.
- Use arrow functions when arguments or short inline logic are needed.
- Keep complicated event logic in separate named functions.
- Use React state setters when user actions need to update the interface.
- Use functional state updates when the next value depends on the previous value.
- Pass handler functions through props when building reusable child components.
- Use meaningful custom callback props such as
onSave or onDelete.
- Use
preventDefault() and stopPropagation() only when their specific behavior is required.
- Use semantic HTML and ensure interactive controls are accessible by keyboard.
20. Practical Project: Interactive Student Manager
This project combines function-based event handling, arguments, state updates, and list rendering. Users can add a student and delete an existing student using buttons.
import { useState } from "react";
function StudentManager() {
const [students, setStudents] = useState([
{ id: 1, name: "Aarav" },
{ id: 2, name: "Priya" }
]);
const [newName, setNewName] = useState("");
function handleNameChange(event) {
setNewName(event.target.value);
}
function handleAddStudent(event) {
event.preventDefault();
const trimmedName = newName.trim();
if (!trimmedName) {
return;
}
const newStudent = {
id: Date.now(),
name: trimmedName
};
setStudents((previousStudents) => [
...previousStudents,
newStudent
]);
setNewName("");
}
function handleDeleteStudent(studentId) {
setStudents((previousStudents) =>
previousStudents.filter((student) => student.id !== studentId)
);
}
return (
<div>
<h2>Student Manager</h2>
<form onSubmit={handleAddStudent}>
<input
value={newName}
onChange={handleNameChange}
placeholder="Enter student name"
/>
<button type="submit">Add Student</button>
</form>
<ul>
{students.map((student) => (
<li key={student.id}>
{student.name}
<button
type="button"
onClick={() => handleDeleteStudent(student.id)}
>
Delete
</button>
</li>
))}
</ul>
</div>
);
}
export default StudentManager;
Project Concepts
handleNameChange() handles input changes.
handleAddStudent() processes form submission.
handleDeleteStudent(studentId) receives a student ID.
map() renders each student.
filter() removes the selected student from the list.
- State setters update the UI after an interaction.
This is a learning example. For a production application, use a reliable unique ID generator or backend-generated IDs instead of relying on Date.now() for guaranteed uniqueness.
21. Difference Between Event Handling and Regular Function Calls
| Feature |
Event Handler Function |
Regular Function Call |
| Execution |
Runs in response to an event when passed as a handler. |
Runs when the code explicitly calls it. |
| Trigger |
Usually a user interaction or browser event. |
Any point in the program where it is called. |
| Example |
onClick={handleClick} |
handleClick() |
| Event object |
Can receive event information from React. |
Receives only the arguments supplied by the caller. |
| Common purpose |
Responding to clicks, input changes, and submissions. |
Performing reusable calculations or other logic. |
22. Interview Questions and Answers
Q1. What is event handling in React?
Event handling is the process of responding to user interactions by assigning functions to event props such as onClick and onChange.
Q2. What is an event handler function?
An event handler function is a function that React executes when its associated event occurs.
Q3. Why do we use onClick={handleClick} instead of onClick={handleClick()}?
The first passes the function for later execution. The second calls the function immediately during rendering.
Q4. Can event handlers update React state?
Yes. Event handlers commonly use state setters such as setCount() to update state after a user action.
Q5. What is the role of arrow functions in event handling?
Arrow functions provide concise inline handlers and allow arguments to be passed when the event occurs.
Q6. Can a parent component pass an event handler to a child?
Yes. The parent can pass a function through props, and the child can connect it to a built-in event prop.
Q7. What is event bubbling?
Event bubbling means that an event propagates from the target element toward ancestor elements, potentially triggering their handlers.
Q8. What is the difference between preventDefault() and stopPropagation()?
preventDefault() prevents a default browser action, while stopPropagation() stops the event from reaching ancestor handlers.
Q9. Why should event handler functions have descriptive names?
Descriptive names make code easier to read, maintain, debug, and understand.
Q10. When should a handler be defined separately instead of inline?
A separate named handler is often preferable when the logic is complex, reused, or easier to understand outside the JSX markup.
23. Practice Exercises
- Create a button that calls a function to display a welcome message.
- Create a counter with Increase and Decrease buttons.
- Create a form that handles input changes and displays the entered text.
- Create a button that passes a product ID to an event handler.
- Create a list with a Delete button for every item.
- Create a reusable button component that receives a handler through props.
- Create a toggle button that shows or hides content.
- Create a form submission handler that prevents the default browser action.
- Create a nested click example and demonstrate event bubbling.
- Build a student manager that supports adding and deleting students.
24. Quick Revision Checklist
- Understand event handling and event handler functions.
- Know how to use
onClick, onChange, and onSubmit.
- Pass function references correctly to JSX event props.
- Know when to use arrow functions and arguments.
- Understand the React event object.
- Update state in response to user interactions.
- Pass event handler functions through component props.
- Understand event bubbling and default browser behavior.
- Use semantic HTML for interactive elements.
- Practice event handling through small React projects.
25. Conclusion
Event Handling with Functions is a fundamental concept in React JS. By defining handler functions and connecting them to JSX event props, developers can make interfaces interactive and responsive to user actions.
Understanding function references, arrow functions, event objects, arguments, props, state updates, and event propagation makes it easier to develop reusable components and practical applications. Practice these techniques by building counters, forms, student lists, product lists, and other interactive React projects.
26. React JS Training and Course Demo
Explore the following resources to learn more about React JS, component interactions, event handling, and application development.