Passing Arguments to Event Handlers in React JS
Passing Arguments to Event Handlers in React JS is a technique used to send additional information to an event handler when a user performs an action, such as clicking a button. These arguments can include an item ID, product name, username, message, index, or any other value required by a function.
In React, event handlers are commonly used with events such as onClick, onChange, and onSubmit. When an event handler needs additional arguments, developers can use arrow functions or the JavaScript bind() method to pass those values when the event occurs.
For example, in a shopping application, each product may have an Add to Cart button. Passing the product ID to the click handler allows React to identify which product the user wants to add.
1. What Are Event Handlers in React?
An event handler is a function that runs in response to a user interaction. React allows event handlers to be assigned to JSX elements using event props such as onClick, onChange, and onSubmit.
Example: Basic Event Handler
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default App;
Explanation
handleClick() is the event handler function.
onClick connects the function to the button's click event.
- React calls the handler when the user clicks the button.
- No additional arguments are passed in this example.
2. What Does Passing Arguments to Event Handlers Mean?
Passing arguments means supplying extra values to a function so it can perform an operation using specific information.
Suppose an application displays three products: Laptop, Mobile, and Tablet. If a user clicks the Delete button beside Mobile, the event handler needs to know which product should be deleted. Passing the product ID or name to the handler provides that information.
Example Without Arguments
function handleClick() {
console.log("Button clicked");
}
Example With an Argument
function handleClick(productName) {
console.log("Selected product:", productName);
}
The second function accepts a parameter named productName. When the function is called with a value, that value becomes available inside the function.
3. Passing Arguments Using an Arrow Function
The most common way to pass an argument to an event handler in a React function component is to wrap the function call inside an arrow function. The arrow function runs when the event occurs and passes the required argument to the handler.
Syntax
<button onClick={() => handleClick(argument)}>
Click Me
</button>
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;
Explanation
greetUser(name) accepts a name as an argument.
- The first button passes
"Rahul".
- The second button passes
"Priya".
- The arrow function delays the function call until the button is clicked.
- Each button can call the same handler with a different argument.
Important: Use onClick={() => greetUser("Rahul")} when you want to pass an argument and run the handler after the click.
4. Difference Between Passing a Function and Calling a Function
One of the most common mistakes in React is calling an event handler directly instead of passing a function for React to execute later.
| Code |
Result |
onClick={handleClick} |
Correct when no extra argument is required. React calls the handler after the click. |
onClick={() => handleClick(id)} |
Correct when you want to pass an argument after the click. |
onClick={handleClick(id)} |
Usually incorrect for event handling because it calls the function during rendering. |
onClick={() => handleClick()} |
Correct, although the arrow function is unnecessary if no extra logic or argument is needed. |
Incorrect Example
function App() {
function handleClick(name) {
alert(name);
}
return (
<button onClick={handleClick("Rahul")}>
Click Me
</button>
);
}
Problem: handleClick("Rahul") executes while React renders the component. The function is not being provided as a click handler.
Correct Example
function App() {
function handleClick(name) {
alert(name);
}
return (
<button onClick={() => handleClick("Rahul")}>
Click Me
</button>
);
}
Result: The handler runs when the user clicks the button, and the value "Rahul" is passed to it.
5. Passing Multiple Arguments to an Event Handler
A function can accept multiple arguments. In React, you can pass several values through an arrow function when an event occurs.
Example
function App() {
function showUser(name, age, city) {
console.log("Name:", name);
console.log("Age:", age);
console.log("City:", city);
}
return (
<button
onClick={() => showUser("Rahul", 25, "Mumbai")}
>
Show User Details
</button>
);
}
export default App;
Explanation
name receives "Rahul".
age receives 25.
city receives "Mumbai".
- The arrow function passes all three values to
showUser().
- The function prints the supplied information in the browser console.
General Syntax
<button onClick={() => handleFunction(value1, value2, value3)}>
Run Function
</button>
6. Passing Arguments Along With the Event Object
React automatically passes an event object to an event handler when the handler is assigned directly. If you wrap the handler in an arrow function to pass your own arguments, you must explicitly pass the event object if the handler also needs it.
Example
function App() {
function handleClick(id, event) {
console.log("Item ID:", id);
console.log("Event type:", event.type);
console.log("Clicked element:", event.currentTarget);
}
return (
<button onClick={(event) => handleClick(101, event)}>
Click Item
</button>
);
}
export default App;
Explanation
101 is the custom argument passed to the handler.
event is the React event object received from the click.
event.type identifies the event type, such as "click".
event.currentTarget identifies the element whose handler is running.
- The handler receives the item ID first and the event object second because that is the order used in the function call.
Remember: React does not automatically insert the event object into the middle of your custom arguments. Pass it explicitly when using an arrow function.
7. Passing Arguments in a List Using map()
React applications frequently display lists of data, such as products, students, employees, tasks, and orders. The map() method can render a button for every item. Passing each item's ID to its event handler allows the application to identify the selected item.
Example: Student List
function StudentList() {
const students = [
{ id: 1, name: "Aarav" },
{ id: 2, name: "Priya" },
{ id: 3, name: "Rahul" }
];
function showStudent(studentId) {
console.log("Selected student ID:", studentId);
}
return (
<div>
<h2>Student List</h2>
{students.map((student) => (
<div key={student.id}>
<span>{student.name}</span>
<button onClick={() => showStudent(student.id)}>
View Details
</button>
</div>
))}
</div>
);
}
export default StudentList;
Explanation
- The
students array contains student IDs and names.
map() creates a row for each student.
key={student.id} gives React a stable key for each rendered list item.
onClick={() => showStudent(student.id)} passes the ID of the relevant student.
- Clicking a student's button logs that student's ID.
8. Passing Arguments to Delete an Item
Passing arguments is especially useful when deleting items from a list. Each Delete button passes the ID of the item that should be removed. React state can then be updated to exclude that item.
Example: Delete a Task
import { useState } from "react";
function TodoList() {
const [tasks, setTasks] = useState([
{ id: 1, title: "Learn React" },
{ id: 2, title: "Practice Events" },
{ id: 3, title: "Build a Project" }
]);
function deleteTask(taskId) {
setTasks((previousTasks) =>
previousTasks.filter((task) => task.id !== taskId)
);
}
return (
<div>
<h2>Todo List</h2>
{tasks.map((task) => (
<div key={task.id}>
<span>{task.title}</span>
<button onClick={() => deleteTask(task.id)}>
Delete
</button>
</div>
))}
</div>
);
}
export default TodoList;
How It Works
- React stores the task list in state.
- Each task has a unique ID.
- Each Delete button passes its task ID to
deleteTask().
filter() creates a new array without the selected task.
setTasks() updates the state.
- React re-renders the list to display the remaining tasks.
9. Passing Arguments to Update an Item
Arguments can also identify which item needs to be updated. For example, a task list may have a Complete button that changes the status of a selected task.
Example: Mark a Task as Completed
import { useState } from "react";
function TaskManager() {
const [tasks, setTasks] = useState([
{ id: 1, title: "Study JSX", completed: false },
{ id: 2, title: "Learn Props", completed: false }
]);
function completeTask(taskId) {
setTasks((previousTasks) =>
previousTasks.map((task) =>
task.id === taskId
? { ...task, completed: true }
: task
)
);
}
return (
<div>
{tasks.map((task) => (
<div key={task.id}>
<span>
{task.title} - {task.completed ? "Completed" : "Pending"}
</span>
<button
onClick={() => completeTask(task.id)}
disabled={task.completed}
>
Complete
</button>
</div>
))}
</div>
);
}
export default TaskManager;
The handler receives the task ID and updates only the matching task. The example uses map() to create a new array and the spread operator to preserve the other properties of the selected task.
10. Passing Arguments Through Component Props
In React, a parent component can pass data and event handler functions to a child component using props. The child can then pass a specific argument to the handler when the user interacts with it.
Example
function UserButton({ userId, onSelect }) {
return (
<button onClick={() => onSelect(userId)}>
Select User
</button>
);
}
function App() {
function handleUserSelect(id) {
console.log("Selected user:", id);
}
return (
<div>
<UserButton userId={501} onSelect={handleUserSelect} />
<UserButton userId={502} onSelect={handleUserSelect} />
</div>
);
}
export default App;
Explanation
App passes a user ID and a handler function to each UserButton.
UserButton receives these values through props.
- When clicked, the child calls
onSelect(userId).
- The parent handler receives the selected user's ID.
- This approach supports reusable components and separates UI from application logic.
11. Passing Arguments Using the bind() Method
JavaScript's bind() method creates a new function with specified arguments supplied before any arguments passed when that function is later called. It can be used to pass arguments to React event handlers.
Syntax
<button onClick={handleClick.bind(null, argument)}>
Click Me
</button>
Example
function App() {
function showMessage(message) {
alert(message);
}
return (
<button onClick={showMessage.bind(null, "Welcome to React")}>
Show Message
</button>
);
}
export default App;
Explanation
bind() returns a new function instead of executing the original function immediately.
null is used for the this value in this simple function-component example.
"Welcome to React" is supplied as the first argument to showMessage().
- The returned function is used as the click handler.
Note: Arrow functions are generally easier to read for this purpose in modern function components. The bind() approach is also relevant in some class-component code.
12. Difference Between Arrow Functions and bind()
| Feature |
Arrow Function |
bind() |
| Example |
onClick={() => handleClick(id)} |
onClick={handleClick.bind(null, id)} |
| Purpose |
Creates a wrapper function that calls the handler with arguments. |
Creates a new function with preset arguments. |
| Readability |
Often straightforward in function components. |
Can be less familiar to beginners. |
| Function execution |
Handler runs when the wrapper is called. |
Bound function runs when the event occurs. |
| Event object |
Can be passed explicitly, for example (event) => handleClick(id, event). |
Additional event arguments are passed after the preset arguments. |
13. Passing String, Number, and Boolean Arguments
Event handlers can receive different JavaScript data types, including strings, numbers, and boolean values.
Example
function App() {
function displayValue(value) {
console.log("Value:", value);
console.log("Type:", typeof value);
}
return (
<div>
<button onClick={() => displayValue("React")}>
Pass String
</button>
<button onClick={() => displayValue(100)}>
Pass Number
</button>
<button onClick={() => displayValue(true)}>
Pass Boolean
</button>
</div>
);
}
export default App;
"React" is a string.
100 is a number.
true is a boolean.
- The
typeof operator reports the type of each value in the console.
14. Passing an Object as an Argument
You can pass an object to an event handler when multiple related values need to be supplied together. This can make the function easier to manage when working with structured data.
Example
function App() {
const product = {
id: 101,
name: "Laptop",
price: 55000
};
function showProduct(item) {
console.log("Product ID:", item.id);
console.log("Product Name:", item.name);
console.log("Price:", item.price);
}
return (
<button onClick={() => showProduct(product)}>
View Product
</button>
);
}
export default App;
When the button is clicked, the object is passed to showProduct(). The handler can access its properties using dot notation.
15. Common Mistakes When Passing Arguments
| Mistake |
Why It Is a Problem |
Correct Approach |
onClick={handleClick(id)} |
Calls the function during rendering. |
onClick={() => handleClick(id)} |
| Forgetting to pass an argument |
The handler may receive undefined if no default is provided. |
Pass the required value explicitly. |
| Passing the event object in the wrong order |
The handler may treat the event as an ID or another value. |
Keep the call's argument order consistent with the function parameters. |
| Changing state directly |
Direct mutation can lead to incorrect UI updates. |
Use the appropriate state setter and create updated arrays or objects. |
| Using an unstable list key |
React may not correctly track list items when items change. |
Use a stable, unique key such as an item ID. |
| Passing a function prop incorrectly |
The child may execute the handler too early or fail to pass the required value. |
Pass a function reference or use an arrow function when arguments are needed. |
16. Best Practices for Passing Arguments
- Use arrow functions to pass arguments to event handlers in function components.
- Pass only the information required by the handler.
- Use descriptive parameter names such as
productId, taskId, and userId.
- Keep function parameter order consistent with the arguments passed in the call.
- Pass the event object explicitly when the handler needs both custom arguments and event details.
- Use stable IDs when working with lists of items.
- Update React state through state setters instead of mutating existing state directly.
- Keep event handlers readable by moving complex logic into named functions.
- Use real HTML buttons for click actions to support keyboard interaction and accessibility.
- Do not use an inline arrow function unnecessarily when a direct function reference is sufficient and no arguments are needed.
17. Practical Project: Product List with Select Buttons
This mini-project demonstrates how to pass a product ID to a click handler. Each product has a button that identifies the selected product and displays its details.
import { useState } from "react";
function ProductList() {
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mobile", price: 25000 },
{ id: 3, name: "Headphones", price: 3000 }
];
const [selectedProduct, setSelectedProduct] = useState(null);
function handleSelectProduct(productId) {
const product = products.find((item) => item.id === productId);
setSelectedProduct(product);
}
return (
<div>
<h2>Available Products</h2>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
<button onClick={() => handleSelectProduct(product.id)}>
Select Product
</button>
</div>
))}
{selectedProduct && (
<div>
<h3>Selected Product</h3>
<p>Name: {selectedProduct.name}</p>
<p>Price: ₹{selectedProduct.price}</p>
</div>
)}
</div>
);
}
export default ProductList;
Project Explanation
- The
products array stores product details.
- The
map() method renders each product with a button.
- The button passes its product ID to
handleSelectProduct().
- The
find() method identifies the selected product.
setSelectedProduct() updates the state.
- Conditional rendering displays the selected product's details.
18. Interview Questions and Answers
Q1. What does passing arguments to event handlers mean in React?
It means supplying values such as IDs, names, or objects to an event handler so it can perform an operation using that information.
Q2. How do you pass an argument to an onClick handler?
Use an arrow function, for example onClick={() => handleClick(10)}.
Q3. Why should we not write onClick={handleClick(id)}?
That expression calls the function during rendering. Use onClick={() => handleClick(id)} to call it when the click occurs.
Q4. Can an event handler receive multiple arguments?
Yes. An arrow function can pass multiple values, such as onClick={() => handleUser(name, age)}.
Q5. How do you pass both an ID and the event object?
Use onClick={(event) => handleClick(id, event)} and define the handler to accept the arguments in that order.
Q6. What is the purpose of bind()?
The JavaScript bind() method creates a new function with a specified this value and optional preset arguments.
Q7. Why is passing an ID useful in a list?
An ID helps identify the exact item that should be selected, deleted, edited, or updated.
Q8. Can an object be passed to an event handler?
Yes. An object can be passed through an arrow function, for example onClick={() => handleProduct(product)}.
Q9. What is the difference between a function reference and a function call?
A function reference provides the function for later execution, while a function call executes it immediately.
Q10. Should state be changed directly inside an event handler?
No. Use React state setters and create updated objects or arrays rather than mutating existing state directly.
19. Practice Exercises
- Create a button that passes your name to a greeting function.
- Create three buttons that pass different numbers to the same handler.
- Render a list of students and pass each student's ID to a View button.
- Create a product list with a Delete button that passes the product ID.
- Create a task list with a Complete button that passes the task ID.
- Write a handler that receives a product ID and the event object.
- Create a button that passes a product object to a handler.
- Build a small application that selects a product and displays its details.
20. Quick Revision Checklist
- Understand what event handlers are in React.
- Know why arguments are passed to event handlers.
- Use arrow functions to pass arguments at event time.
- Understand the difference between passing and calling a function.
- Pass multiple arguments when required.
- Pass the event object explicitly when using a wrapper function.
- Use item IDs to select, update, or delete items from lists.
- Understand how
bind() can preset arguments.
- Use props to pass event handlers between parent and child components.
- Update state immutably and use stable keys when rendering lists.
21. Conclusion
Passing Arguments to Event Handlers is an important React JS concept that allows functions to receive the exact information needed to respond to user interactions. Using arrow functions, developers can pass values such as IDs, names, numbers, and objects to event handlers at the time an event occurs.
This technique is particularly useful for rendering dynamic lists, deleting or updating items, selecting products, managing tasks, and building reusable components. Practicing these patterns will help you write clearer and more effective React applications.
22. React JS Training and Course Demo
Learn more about React JS, event handling, component interactions, props, and state management through the following course resources.