Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Typescript: SetState inside React.FC to change value in React.Component

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'.
    };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading