Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing state from parent to child functional React Component

I’m trying to refactor some code into separate components using Typescript / React but am having trouble sharing state between components. I’m trying to update a boolean between components and am curious about the best way to go about this.

The state can be set in either the parent or child. I’m using the useState hook in the parent component and then trying to set the state in the child component. In my child component, I’m getting the error cannot find setState.

In my parent component I’m declaring my state using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [state, setState] = React.useState({
    loggedIn: false,
  });

I’m trying to pass state to the child component via props with:

      <div> <ChildComponent {...state}/> </div> // trying to pass in props, but not sure how to also pass in setting state. 

I’m not sure how to allow state changes in the child component:

export const ChildComponent = (state: boolean) => { 
    setState(true)
}

Any help is appreciated.

>Solution :

Here is simple sandbox where you can see how to pass state from parent to child component, and how to change parent state inside child component -> https://codesandbox.io/s/autumn-glitter-k9b1jc?file=/src/App.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading