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:
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