Home > Mobile >  Passing state from parent to child functional React Component
Passing state from parent to child functional React Component

Time:09-21

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.

CodePudding user response:

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

CodePudding user response:

First you should not pass states like this, you can use global state management for it. But by this way of passing state you can do it as props like:

<ChildComponent state={state.loggedIn}/>

and

export const ChildComponent = ({state}) => { 
    ...
}

CodePudding user response:

There you go:

Parent.tsx

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

  return <Child state={state} setState={setState} />;
}

Child.tsx

type Props = {
  state: { loggedIn: boolean };
  setState: React.Dispatch<
    React.SetStateAction<{
      loggedIn: boolean;
    }>
  >;
};

export default function Child({ state, setState }: Props) {
  return <div>Child</div>;
}

CodePudding user response:

you should add constructor with "props" to your child component and by this you can reach the parent state:

class ChildComponent extends Component {
   constructor(props) {
   super(props);
   this.state = {
     ...
   };   
}

in your code you can use this.props.propertyYouWantToUse

CodePudding user response:

Pass the setState function to the child component

  • Related