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.
0
0
Passing arguments to handlers in React
Introduction
You want to know which button was clicked in a list of buttons.
You need to send a specific value when a user submits a form.
You want to pass an ID to a function when clicking an item.
You want to customize behavior based on user input or selection.
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
This example passes the name 'Alice' to the greet function when the button is clicked.
React
function greet(name) { alert(`Hello, ${name}!`); } <button onClick={() => greet('Alice')}>Greet Alice</button>
Here, the number 42 is passed as an argument to the showId handler.
React
function showId(id) { console.log('Clicked item id:', id); } <button onClick={() => showId(42)}>Show ID</button>
This example passes the event object and a message string to the handler.
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> ); }
OutputSuccess
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.