Borislav Hadzhiev
Thu Apr 21 2022·2 min read
Photo by Jaizer Capangpangan
To pass an onChange event handler to a child component in React:
<Child handleChange={handleChange} />
.onChange
prop on the input field in the child.import {useState} from 'react'; function Child({handleChange}) { return ( <input id="message" name="message" onChange={handleChange} /> ); } export default function App() { const [message, setMessage] = useState(''); function handleChange(event) { setMessage(event.target.value); } return ( <div> <Child handleChange={handleChange} /> <h2>Message is: {message}</h2> </div> ); }
We passed a handleChange
function to a child component.
If you pass the result of calling the function, e.g.
handleChange={handleChange()}
, then it would get invoked immediately on page
load, which is not what we want.
If you want to pass a parameter to the function that you are passing as a prop, use an inline arrow function.
import {useState} from 'react'; function Child({handleChange}) { return ( <input id="message" name="message" onChange={handleChange} /> ); } export default function App() { const [message, setMessage] = useState(''); function handleChange(event, anotherParam) { console.log(anotherParam); setMessage(event.target.value); } return ( <div> <Child handleChange={event => handleChange(event, 'another param')} /> <h2>Message is: {message}</h2> </div> ); }
We passed a parameter to the handleChange
function when passing it as a prop
to the Child
component. However, note that we are still passing a function as
a prop, and not the result of calling one.
You can also add extra functionality to the function you passed as a prop in the child component.
import {useState} from 'react'; function Child({handleChange}) { function wrapHandleChange(event) { console.log('Child triggered onChange'); // 👉️ your logic before handleChange(event); // 👉️ your logic after } return ( <input id="message" name="message" onChange={wrapHandleChange} autoComplete="off" /> ); } export default function App() { const [message, setMessage] = useState(''); function handleChange(event) { setMessage(event.target.value); } return ( <div> <Child handleChange={handleChange} /> <h2>Message is: {message}</h2> </div> ); }
We wrapped the handleChange
function into another function where we can run
some extra logic before calling it or after.
This is useful when you have to await the return value of a Promise, or run some logic based on the value of the input field.