Suppose I have a Dropdown
component. Initally, I placed that Dropdown
component in a Parent component and created my handleChange
function and everything works fine. However, I want to abstract that Dropdown
component into its own custom Child component and now my Parent component calls that Child component.
Now I am wondering how can I pass that handleChange
function from my Parent component to my Child component in a way where I can update that handleChange
function to update the states in the Child component. Not sure how to proceed with this? Do I need to use useCallBack
function? Or something else?
const ParentComponent = () => {
const identifierValue = useState([]);
...there are more states here.
const handleChange = (_, items) => {
//updates different states here
};
return (
<ChildComponent
selectedItem={identifierValue}
onChange={handleChange}
/>
);
};
export default ParentComponent;
const ChildComponent = ({ identifierValue, handleIdentifierChange }) => {
const handleChange = (_, items) => {
//I want to update the Child component states here
};
return (
<Dropdown
selectedItem={identifierValue}
onChange={handleChange}
/>
);
};
export default ChildComponent;
3
Answers
In the Parent component, only pass
handleChange
andidentifierValue
In the Child component, only retrieve
handleChange
andidentifierValue
You can do a
props.onChange()
call inside of yourhandleChange
function that is defined in the ChildComponent. If you’re trying to access state setters inside of the ChildComponent that are defined in the ParentComponent, you could also pass in the state setters from the parent to the child as props.Let’s assume that the
handleChange
event will be triggered by an action in the Dropdown component.If you wish to only update the states in the parent component, here is an implementation :
Alternatively, if you want to update states in both the child and parent components, consider the following implementation :