Passing arguments to handlers lets you send extra information when a user interacts with your app. This helps your app respond in the right way.
Passing arguments to handlers in React
Introduction
Syntax
React
function handleClick(arg) { // use arg here } <button onClick={() => handleClick(value)}>Click me</button>
Use an arrow function inside onClick to pass arguments without calling the function immediately.
Avoid calling the handler directly like onClick={handleClick(value)} because it runs right away.
Examples
React
function greet(name) { alert(`Hello, ${name}!`); } <button onClick={() => greet('Alice')}>Greet Alice</button>
React
function showId(id) { console.log('Clicked item id:', id); } <button onClick={() => showId(42)}>Show ID</button>
React
function handleEvent(event, message) { event.preventDefault(); alert(message); } <button onClick={(e) => handleEvent(e, 'Button clicked!')}>Click me</button>
Sample Program
This component shows three buttons for colors. When you click a button, it passes the color name to the pickColor handler, which updates the displayed selected color.
React
import React, { useState } from 'react'; export default function ColorPicker() { const [color, setColor] = useState('None'); function pickColor(chosenColor) { setColor(chosenColor); } return ( <div> <p>Selected color: {color}</p> <button onClick={() => pickColor('Red')}>Red</button> <button onClick={() => pickColor('Green')}>Green</button> <button onClick={() => pickColor('Blue')}>Blue</button> </div> ); }
Important Notes
Using arrow functions inside event handlers is a common way to pass arguments.
Be careful not to call the handler function directly in JSX, or it will run immediately.
You can pass multiple arguments by wrapping them in an arrow function.
Summary
Passing arguments to handlers lets you send extra info when users interact.
Use arrow functions in JSX to pass arguments without running the function right away.
This helps make your app respond correctly to different user actions.
Practice
1. What is the correct way to pass an argument
id to a click handler in React without calling the function immediately?easy
Solution
Step 1: Understand function call vs function reference
UsinghandleClick(id)calls the function immediately, which is not desired on render.Step 2: Use arrow function to delay call
Wrapping the call in an arrow function() => handleClick(id)passes a function reference that callshandleClickwithidonly when clicked.Final Answer:
onClick={() => handleClick(id)} -> Option BQuick Check:
Use arrow function to pass argument without immediate call [OK]
Hint: Wrap call in arrow function to pass args without running [OK]
Common Mistakes:
- Calling function directly in JSX causing immediate execution
- Using bind incorrectly without context
- Passing function reference without arguments
2. Which of the following is the correct syntax to pass multiple arguments
event and id to a handler handleClick in React?easy
Solution
Step 1: Recognize event parameter handling
The event object is passed automatically by React to the event handler, so it must be received as a parameter.Step 2: Use arrow function to pass extra argument
Using(event) => handleClick(event, id)correctly receives the event and passes both event and id to the handler.Final Answer:
onClick={(event) => handleClick(event, id)} -> Option DQuick Check:
Arrow function with event param passes multiple args correctly [OK]
Hint: Use arrow with event param to pass event plus extra args [OK]
Common Mistakes:
- Calling handler directly causing immediate execution
- Using bind with wrong argument order
- Ignoring event parameter in arrow function
3. Given the code below, what will be logged when the button is clicked?
function MyButton() {
const handleClick = (id) => {
console.log('Clicked id:', id);
};
return <button onClick={() => handleClick(5)}>Click me</button>;
}medium
Solution
Step 1: Understand the arrow function usage in onClick
The onClick uses an arrow function that callshandleClick(5)when clicked, passing 5 as argument.Step 2: Check what handleClick logs
handleClick logs the string plus the passed id, so it logs 'Clicked id: 5'.Final Answer:
Clicked id: 5 -> Option AQuick Check:
Arrow function calls handler with 5, logs 'Clicked id: 5' [OK]
Hint: Arrow function calls handler with argument on click [OK]
Common Mistakes:
- Expecting immediate log on render
- Confusing function reference with function call
- Ignoring argument passed inside arrow function
4. Identify the error in this React code snippet:
function ListItem({ id }) {
return <li onClick={handleClick(id)}>Item {id}</li>;
function handleClick(id) {
alert('Clicked ' + id);
}
}medium
Solution
Step 1: Check how onClick is assigned
UsingonClick={handleClick(id)}callshandleClickimmediately during render, which is wrong.Step 2: Correct way to assign onClick
It should be wrapped in a function likeonClick={() => handleClick(id)}to call on user click.Final Answer:
handleClick is called immediately during render, not on click -> Option CQuick Check:
Direct call in JSX runs function immediately, must wrap in arrow [OK]
Hint: Wrap handler call in arrow to avoid immediate execution [OK]
Common Mistakes:
- Calling handler directly in JSX
- Misplacing function definition
- Thinking alert syntax is wrong
5. You want to create a list of buttons that alert their own index when clicked. Which code correctly passes the index to the handler without causing all alerts on render?
const List = () => {
const handleClick = (index) => alert(`Button ${index} clicked`);
return (
<div>
{[0,1,2].map((i) => (
<button key={i} onClick={/* ??? */}>Button {i}</button>
))}
</div>
);
};hard
Solution
Step 1: Avoid immediate call in map
UsinghandleClick(i)calls the function immediately during render, causing all alerts at once.Step 2: Use arrow function to pass index on click
Wrapping in() => handleClick(i)delays the call until the button is clicked, passing the correct index.Final Answer:
onClick={() => handleClick(i)} -> Option AQuick Check:
Arrow function passes index on click, prevents immediate call [OK]
Hint: Use arrow function in map to pass index without immediate call [OK]
Common Mistakes:
- Calling handler directly in map causing immediate alerts
- Passing handler without arguments losing index info
- Using bind with incorrect context
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
