How do I prevent Material UI Dialog from being dismissed upon clicking the backdrop?

Viewed 11433

I have a React JS app that uses the Dialog component and I cannot seem to find any documentation on how I can prevent the dialog from being automatically dismissed by merely clicking the backdrop. I have an explicit action within the dialog that I want to use for control of the dismissal.

I have tried reading the docs and of course searching here but am not finding anything helpful or that contains an example. Any help is appreciated; this is my first time using React.

<Dialog onClose={handleClose} aria-labelledby="simple-dialog-title" open={open}>
  <DialogTitle id="simple-dialog-title">Uploading Media To Server</DialogTitle>
  <React.Fragment>
    <Grid container alignItems="center" justify="center">          
        <img src={LoadingGif} width="150" />
    </Grid>
  </React.Fragment>
</Dialog>

There was mention of this being a possible duplicate of How to handle "outside" click on Dialog (Modal) with material-ui but do not find it helpful as I am using a Dialog component instead of a Modal.

1 Answers

Material 4

Try this:

<Dialog onClose={handleClose} aria-labelledby="simple-dialog-title" 
  open={open} onBackdropClick="false">
   <DialogTitle id="simple-dialog-title">Uploading Media To Server</DialogTitle>
   <React.Fragment>
      <Grid container alignItems="center" justify="center">          
        <img src={LoadingGif} width="150" />
      </Grid>
   </React.Fragment>
</Dialog>

You can also achieve it setting disableBackdropClick="true", which maybe is more appropriate for your use case.

Material 5

onBackdropClick and disableBackdropClick were deprecated in Material v5, use this instead:

   <Dialog onClose={handleClose} aria-labelledby="simple-dialog-title" 
      open={open}>
       <DialogTitle id="simple-dialog-title">Uploading Media To Server</DialogTitle>
       <React.Fragment>
          <Grid container alignItems="center" justify="center">          
            <img src={LoadingGif} width="150" />
          </Grid>
       </React.Fragment>
    </Dialog>

And checking whether the backdrop was clicked in the onClose handler:

const handleClose = (event, reason) => {
    if (reason && reason == "backdropClick") 
        return;
    myCloseModal();
}
Related