reactjstypescriptreact-propsprop

Why does the prop not change to true?


If I call this in parent comp:

 private addEmployeeForm() {
return <AddEmployeeComp employees={this.state.employees} showForm={true} />;


}

And then AddEmployeeComp:

    export class AddEmployeeComp extends React.Component<
  { employees: Employee[]; showForm: boolean },
  {
    
    showEmployeeForm: boolean;
  }
> {
  
  constructor(props: { employees: Employee[]; showForm: boolean }) {
    super(props);
    this.state = {
      showEmployeeForm: this.props.showForm,
    };
  }




   private handleClose() {
    this.setState({
      showEmployeeForm: false,
    });
  }

  public render() {
    return (
      <>
        {this.state.showEmployeeForm ? (
          <div className="popup-box">
            <div className="box">
              <span className="close-icon" onClick={() => this.handleClose()}>
                x
              </span>
              <div className="userNameDiv">
                <label className="labelUsername" htmlFor="username">
                  Username
                </label>
                <br />
    ...

Why does the showForm={true} not apply, once I closed the Formular (AddEmployeeCmp) and I want to open it again. showForm is after the first open always set to false. How could I change it to true again (from parent comp)?


Solution

  • showForm is props and showEmployeeForm is state. showForm only initializes showEmployeeForm. If you want parent know its child componet's state change, you may need to lift the state up. See React doc sharing-state-between-components and lifting-state-up.