Last updated: Apr 7, 2024
Reading time·2 min
To pass multiple parameters to onChange in React:
onChange
prop.event
object.handleChange
function and pass it the event and the rest of the
parameters.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;
We set the onChange
prop on the input element, so every time its value
changes, the handleChange
function is invoked.
<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.
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.
const handleChange = (event, param1, param2) => { setMessage(event.target.value); console.log(event.target.value); console.log(param1); console.log(param2); };
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.