How to Pass Parameter to Event Handler in React
In React, you can pass parameters to an event handler by using an arrow function like
onClick={() => handleClick(param)} or by using bind like onClick={handleClick.bind(null, param)}. This lets you send extra data to the handler when the event happens.Syntax
There are two common ways to pass parameters to event handlers in React:
- Arrow function: Wrap the handler call inside an arrow function to pass parameters.
- bind method: Use
bindto preset parameters for the handler.
Both methods create a new function that React calls on the event.
jsx
/* Arrow function syntax */ <button onClick={() => handleClick(param)}>Click me</button> /* bind method syntax */ <button onClick={handleClick.bind(null, param)}>Click me</button>
Example
This example shows a button that passes a name parameter to the event handler and displays an alert with that name.
jsx
import React from 'react'; function App() { const handleClick = (name) => { alert(`Hello, ${name}!`); }; return ( <div> <button onClick={() => handleClick('Alice')}>Greet Alice</button> <button onClick={handleClick.bind(null, 'Bob')}>Greet Bob</button> </div> ); } export default App;
Output
When clicking 'Greet Alice' button, an alert shows: "Hello, Alice!". When clicking 'Greet Bob' button, an alert shows: "Hello, Bob!".
Common Pitfalls
Common mistakes include:
- Calling the handler directly instead of passing a function, like
onClick={handleClick(param)}, which runs immediately on render. - Not using an arrow function or bind, so parameters are not passed.
Always pass a function reference or create a new function to avoid immediate execution.
jsx
/* Wrong: calls handleClick immediately on render */ <button onClick={handleClick('Alice')}>Wrong</button> /* Right: pass a function that calls handleClick on click */ <button onClick={() => handleClick('Alice')}>Right</button>
Quick Reference
Tips for passing parameters to event handlers in React:
- Use arrow functions for simple and readable code.
- Use
bindif you prefer presetting parameters. - Avoid calling the handler directly in JSX to prevent unwanted execution.
- Remember that arrow functions create a new function on each render, which is usually fine for most cases.
Key Takeaways
Use arrow functions or bind to pass parameters to React event handlers.
Never call the event handler directly in JSX; always pass a function reference.
Arrow functions are the simplest and most common way to pass parameters.
bind can be used but is less common and slightly less readable.
Passing parameters lets you customize handler behavior based on user actions.