Passing multiple parameters to onChange in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Passing multiple parameters to onChange in React

To pass multiple parameters to onChange in React:

  1. Pass an arrow function to the onChange prop.
  2. The arrow function will get called with the event object.
  3. Call your handleChange function and pass it the event and the rest of the parameters.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleChange = (event, param1, param2) => { setMessage(event.target.value); console.log(event.target.value); console.log(param1); console.log(param2); }; return ( <div> <input id="message" name="message" value={message} onChange={event => handleChange(event, 'hello', 'world')} /> </div> ); }; export default App;

passing multiple parameters to onchange

The code for this article is available on GitHub

We set the onChange prop on the input element, so every time its value changes, the handleChange function is invoked.

App.js
<input id="message" name="message" value={message} onChange={event => handleChange(event, 'hello', 'world')} />

Notice that we are passing a reference to the function to the prop, and not the result of calling the function.

If you pass the result of calling the function, then the event handler would get invoked immediately when the page loads, which is not what we want.

The function we passed to the onChange prop will get invoked with the event object, so we have to pass the event to our handleChange function and then pass it any other values it needs access to.

App.js
const handleChange = (event, param1, param2) => { setMessage(event.target.value); console.log(event.target.value); console.log(param1); console.log(param2); };
The code for this article is available on GitHub

The same approach can be used when you have to pass multiple parameters to other event handler functions, e.g. onClick.

It is very important to not pass the result of calling the handleChange function to the onChange prop because then the function would get invoked immediately as the page loads and that could cause an infinite re-render loop.

If you need to handle the onChange event on a select element, click on the link and follow the instructions.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.