Borislav Hadzhiev
Tue Apr 26 2022·2 min read
Photo by Alex Grodkiewicz
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.
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.
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.