Close Modal in UI React on Cancel button

10.1k Views Asked by At

I am following https://react.semantic-ui.com/modules/modal to create a Modal form.

I want to close the Modal when click on the Cancel button. I am restricted not to use the shorthand method suggested in the link above. How should I write the handleClose() function in order to close the Modal form?

handleClose = () => {
   console.log("close")
}

render(){
    return(
      <Modal trigger={<Button>Upload</Button>}closeIcon>
      <Modal.Content>
        <p>Please upload a valid file.</p>
        <Form.Input
          name="upload"
          label=""
          type="file"
          onChange={e =>
            this.setState({file_data : e.target.files[0]})}
        >
        </Form.Input>

      </Modal.Content>
      <Modal.Actions>
        <Button onClick = {this.handleClose}>Cancel
        </Button>
        <Button positive onClick = {this.handleUpload}>Upload
        </Button>
      </Modal.Actions>
    </Modal>
    );
  }
1

There are 1 best solutions below

1
On BEST ANSWER

I actually solved it. I initialize a variable in state which model_open : false and then declare two function for it.

handleOpen = () => {
    this.setState({ model_open: true })
}

handleClose = () => {
    this.setState({ model_open: false })
}

Then I just call these method based on use case.

render(){
  return(
    <Modal
    trigger={<Button onClick={this.handleOpen}>Upload</Button>}
    open={this.state.model_open}
    onClose={this.handleClose}
    closeIcon>
    <Modal.Content>
      <p>Please upload a valid file.</p>
      <Form.Input
        name="upload"
        label=""
        type="file"
        onChange={e =>
          this.setState({file_data : e.target.files[0]})}
      > 
      </Form.Input>

    </Modal.Content>
    <Modal.Actions>
      <Button onClick = {this.handleClose}>Cancel
      </Button>
      <Button positive onClick = {this.handleUpload}>Upload
      </Button>
    </Modal.Actions>
  </Modal>
  );
}