Tom Rudge
Tom Rudge

Reputation: 3272

React setstate not firing to close MUI dialog

My dialog used from Material UI has been set up in its own component unlike the demos provided - https://material-ui.com/demos/dialogs/

I can open the dialog and the state changes from false to true. I've added a handleClose for the close which should set the state back to false... but comes back true again. Can anybody point out to what I've done wrong here?

https://codesandbox.io/s/zlmj2k3pom

this.state = {
  open: false
};

state = {
  open: false
};

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

Upvotes: 1

Views: 1511

Answers (2)

Tholle
Tholle

Reputation: 112777

Instead of duplicating the open state in the VehicleDialog component you can use the open and onClose props given to it to close the modal.

Example

class VehicleDialog extends Component {
  render() {
    const { open, id, onClose } = this.props;

    return (
      <React.Fragment>
        <Dialog aria-labelledby="customized-dialog-title" open={open}>
          <DialogTitle id="customized-dialog-title">Modal title</DialogTitle>
          <DialogContent>
            <Typography gutterBottom>
              Cras mattis consectetur purus sit amet fermentum. Cras justo odio,
              dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta
              ac consectetur ac, vestibulum at eros.
            </Typography>
            <Typography gutterBottom>
              Praesent commodo cursus magna, vel scelerisque nisl consectetur
              et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor
              auctor.
            </Typography>
            <Typography gutterBottom>
              Aenean lacinia bibendum nulla sed consectetur. Praesent commodo
              cursus magna, vel scelerisque nisl consectetur et. Donec sed odio
              dui. Donec ullamcorper nulla non metus auctor fringilla.
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button color="primary" onClick={() => onClose(id)}>
              Close
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    );
  }
}

Upvotes: 1

lankovova
lankovova

Reputation: 1426

You are using open variable from props in your render, so changing state.open has no effect.

  render() {
    const { open, id } = this.props;

I suggest you to do next things:

  1. Set state = { open: this.props.open } in constructor
  2. Then use state.open variable in render function

Upvotes: 1

Related Questions