Home > Software engineering >  React Typescript: SetState inside React.FC to change value in React.Component
React Typescript: SetState inside React.FC to change value in React.Component

Time:12-23

I have an React.Component with an state modalVisible to open an Modal:

<Modal
   visible={this.state.modalVisible}
>
   <FormStructure
      record={this.state.selectedRecord}
      question={this.state.question}
      dropdownItems={this.state.dropdownItems}
   />
</Modal>

After the Modal opens the React.FC <FormStrucutre ... /> gets rendered and the Problem is that I dont know how to change the state value modalVisible inside the React.FC:

 const Submit = () => {
        fetch('api/Call/Save', {
            headers: { 'Content-Type': 'application/json' },
            method: 'POST',
            body: JSON.stringify({
                'No': form.getFieldValue('no')
            })
        })
            .then(() => this.setState({modalVisible: false}); //TS2532  (TS) Object is possibly 'undefined'.
    };

CodePudding user response:

You have to pass the closeModal method to React.FC <FormStructure />

// class component

<Modal
   visible={this.state.modalVisible}
>
   <FormStructure
      record={this.state.selectedRecord}
      question={this.state.question}
      dropdownItems={this.state.dropdownItems}
      closeModal={() => this.setState({modalVisible: false})}
   />
</Modal>

Use the props in FormStructure

// FormStructure.tsx

const FormStructure = (props: any) => {
  const {record, question, dropdownItems, closeModal} = props;

  const onSubmit = () => {
     ....
     closeModal();
  }

}

CodePudding user response:

A common pattern is to pass callbacks in as props, and child components call callbacks when events happen. In this case you could expose an onSave prop:

// parent
<Modal
   visible={this.state.modalVisible}
>
   <FormStructure
      record={this.state.selectedRecord}
      question={this.state.question}
      dropdownItems={this.state.dropdownItems}
      onSave={() => this.setState({modalVisible: false})}
   />
</Modal>


// child
class FormStructure extends React.Component {
   const Submit = () => {
        fetch('api/Call/Save', {
           // ...
        })
            .then(() => this.props.onSave();
    };
}

  • Related