How to disable outside click on a modal with React Material-UI?

Sometimes, we want to disable outside click on a modal with React Material-UI.

In this article, we’ll look at how to disable outside click on a dialog (Modal) with React Material-UI.

How to disable outside click on a dialog modal with React Material-UI?

To disable outside click on a dialog modal with React Material-UI, we can set the onClose prop of the Modal to a function that has the reason as the 2nd parameter.

Then we can check that the reason isn’t 'backdropClick' before we close it.

For instance, we write:

import * as React from "react";
import Modal from "@material-ui/core/Modal";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  paper: {
    position: "absolute",
    backgroundColor: theme.palette.background.paper,
    border: "2px solid #000",
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3)
  }
}));

export default function App() {
  const [open, setOpen] = React.useState(false);
  const classes = useStyles();

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <button type="button" onClick={handleOpen}>
        Open Modal
      </button>
      <Modal
        open={open}
        onClose={(_, reason) => {
          if (reason !== "backdropClick") {
            handleClose();
          }
        }}
      >
        <div className={classes.paper}>
          <p>hello world</p>
          <button type="button" onClick={handleClose}>
            Close Modal
          </button>
        </div>
      </Modal>
    </div>
  );
}

We call makeStyles with an object with some styles to return the useStyles hook.

Then we add the Modal component into App, which is opened by clicking on the Open Modal button.

The open state is controlled by the open prop.

The handleOpen function sets open to true to open the modal.

And the handleClose function sets open to false to close it.

Next, we add the Modal component to add the modal.

We set the open prop to open to control when it’s opened or closed.

And we set the onClose prop to a function that checks if the reason isn’t 'backdropClick'.

If it isn’t, we call handleClose to close the modal.

In the Modal we add a div with the content.

It has the Close Modal button that has the onClick prop set to handleClose to close the modal when we click it.

As a result, only clicking on the Close Modal button will close the modal.

Conclusion

To disable outside click on a dialog modal with React Material-UI, we can set the onClose prop of the Modal to a function that has the reason as the 2nd parameter.

Then we can check that the reason isn’t 'backdropClick' before we close it.