Passing multiple parameters to onChange in React

avatar

Borislav Hadzhiev

Tue Apr 26 20222 min read

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

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

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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.