0

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;
  • 2
    Usually, you change the state of the child components by passing props, so if each children has its own local state that needs to be managed by the parent, you should look into [_lifting the state up_](https://reactjs.org/docs/lifting-state-up.html). – Emile Bergeron Feb 24 '21 at 20:16
  • Does this answer your question? [React js change child component's state from parent component](https://stackoverflow.com/questions/39041710/react-js-change-child-components-state-from-parent-component) – Emile Bergeron Feb 24 '21 at 20:17
  • Please remember to use a react fragment to render multiple children without adding html. – evolutionxbox Feb 24 '21 at 20:23

1 Answers1

1

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>;
};
Michael M.
  • 500
  • 5
  • 10
  • 1
    The last code example doesn't change the child state, if `passedProp` updates. It only initialises the state with the value provided during the first render. To update it you would have to explicitly do that in e.g. `useEffect`. – trixn Feb 24 '21 at 20:26
  • `onClick={setPropToPass('prop')}` should be `onClick={() => setPropToPass('prop')}` – Emile Bergeron Feb 24 '21 at 20:31