How to Disable MUI Dialog Backdrop Clicks

The Material-UI Dialog component is composed of several MUI components, including a Backdrop. The Backdrop obscures the rest of the screen and prevents user interaction with other UI elements. By default, MUI closes the Dialog if the Backdrop is clicked.

If you need to force the user to interact with the Dialog, you don’t want it to close when there is a click outside the Dialog (on the Backdrop). In this example, I require the user to either press the ‘ok’ or ‘cancel’ button to close the Dialog.

Handle Click Outside Modal
Handle Click Outside Modal

The code in this example builds on this post where I enable every MUI Dialog prop.

I was able to disable the Backdrop close on click by using the Dialog’s onClose handler. We can’t disable it directly in the onBackdropClick handler.

The onBackdropClick handler only passes the click event. I attempted to use this handler to disable close on Backdrop click but I was unsuccessful. Even using event.stopPropagation() failed. This handler seems to be a niche use case.

Since I couldn’t stop the onBackdropClick handler from bubbling the event to the Dialog onClose handler, I blocked the close in the Dialog onClose handler. The Backdrop click passed a reason prop value of ‘backdropClick’. I check against this value and don’t close when a Backdrop click occurs.

//state and functions
const [open, setOpen] = React.useState(false);

const handleClose = (
  event: {},
  reason: "backdropClick" | "escapeKeyDown"
) => {
  if (reason === "backdropClick") {
    console.log(reason);
  } else {
    setOpen(false);
  }
};

const handleBackdropClick = () => {
  //these fail to keep the modal open
  event.stopPropagation();
  return false;
};

//JSX
<Dialog
  onClose={handleClose}
  onBackdropClick={handleBackdropClick}
  disableEscapeKeyDown
/>

Remember that a Close or OK button click (like in my Dialog Example) doesn’t pass a reason value, so we do want to close when reason is undefined.

Here’s an example of styling the MUI Drawer, which is also a modal.

MUI Dialog Docs API

Share this post:

2 thoughts on “How to Disable MUI Dialog Backdrop Clicks”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.