Home > database >  Passing state from child to parent component in react
Passing state from child to parent component in react

Time:03-02

I have a parent and child component, i want to pass the state(share) from the child component to the parent one in the props(isChecked), how can this be done?

export class Form extends React.Component<FormProps, {
    ...,
    isChecked?: boolean}> {
constructor(props: FormProps) {
    super(props);

    this.state = {
      ...,
      isChecked:false
    };
 render() {

}
return <div><Input name="Name" required={true} isChecked={this.state.isChecked}></div>
}

export function Input(props: React.PropsWithChildren<{name: string, required?: boolean, isChecked?:boolean}>) {
 
  const [share, setShare] = useState(false);
 
  return <Fragment>
    <div>
      {props.name}
      <span onClick={(event) => {setShare(!share);props.isChecked = share;}}>Selection {props.required ? '(Required)': ''}</span>
    </div>
  </Fragment>;
}

CodePudding user response:

I guess you want to use share in your parent component and if that's the case you must set the state in the parent and pass it to your child as a prop just as you did with isChecked.

CodePudding user response:

For Child to Parent Interaction, you should pass a function as prop to the child from parent..

export class Form extends React.Component<FormProps, {
        ...,
        isChecked?: boolean}> {
    constructor(props: FormProps) {
        super(props);
    
        this.state = {
          ...,
          isChecked:false
        };
     render() {
    
       return <div>
               <Input 
                 name="Name" 
                 required={true} 
                 isChecked={this.state.isChecked}
                 handleChecked={
                 (isChecked: boolean) => this.setState({isChecked})
                 }
                />
             </div>
    }
    

    export function Input(props: React.PropsWithChildren<{name: string, required?: boolean, isChecked?:boolean, handleChecked: (isChecked: boolean) => void}>) {
     
      const [share, setShare] = useState(false);
     
      return <Fragment>
        <div>
          {props.name}
          <span onClick={
              (event) => {
                  setShare(!share);
                  handleChecked(share);
          }}>Selection {props.required ? '(Required)': ''}</span>
        </div>
      </Fragment>;
    }
  • Related