How can I change all the children's component states simultaneously from the parent component?
const ParentComponent = () =>{
<Child1/>
<Child2/>
<Child3/>
<button>change children's state</button>
}
export default ParentComponent;
How can I change all the children's component states simultaneously from the parent component?
const ParentComponent = () =>{
<Child1/>
<Child2/>
<Child3/>
<button>change children's state</button>
}
export default ParentComponent;
There really isn't a need to set a child's state depending on something the parent does. That is what props are for.
const ParentComponent = () => {
const [propToPass, setPropToPass] = useState('');
return (
<>
<Child1 passedProp={propToPass} />
<Child2 passedProp={propToPass} />
<Child3 passedProp={propToPass} />
<button onClick={() => setPropToPass('prop')}>change children's state</button>
</>
);
};
And then in your child component you can use the prop.
const Child1 = ({ passedProp }) => {
return <div>passedProp</div>;
};
Or if you really want to change the state depending on props. Edit: As someone has pointed out in the comments, this would only initialize state and not update state when prop is changed. So just directly accessing the props would be a better idea.
const Child1 = ({ passedProp }) => {
const [someState, setSomeState] = useState(passedProp);
return <div>someState</div>;
};