Adam
Adam

Reputation: 2552

React - Enable background scrolling when Material UI Dialog is open

I've got a component that opens and closes a Material UI Dialog. At the moment, there is text that is displayed on the page followed by a button that simply opens the dialog. I've created a code sandbox to highlight where I am with this: https://codesandbox.io/s/formdialog-material-demo-forked-cgjgh?file=/demo.js:0-8775

When the dialog is open, is it possible to enable scrolling in the background (i.e. on the main page) so that the user can scroll through the text as an example? I've included the hideBackdrop prop to be true so that the backdrop is hidden, but I'm not sure how to to do it so the scrolling on the main page can be enabled.

Upvotes: 1

Views: 9202

Answers (3)

mohsin hussain
mohsin hussain

Reputation: 13

you can mange scrolling by using React Hook useEffect.

 const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event, item) => {
    setAnchorEl(event.currentTarget);
  };

  const open = Boolean(anchorEl);

Now whenever a click will happen "open" will be true OR you might be using some other state method to open the Material UI Dialog by managing state.

So here is the useEffect Method

 useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "scroll";
    }
  }, [open]);

Upvotes: 1

rakram
rakram

Reputation: 66

For me setting "disableScrollLock" property to true solved the problem. I found it under Material UI Modal documentation: https://mui.com/material-ui/api/modal/

<Dialog open={open} 
        onClose={handleClose} 
        hideBackdrop={true}
        disableScrollLock
  >

I tested it in your CodeSandbox example and it worked as it was supposed to. Hope this helps with your problem!

Upvotes: 5

WebEXP0528
WebEXP0528

Reputation: 601

Please disable overflow:hidden style property of body tag when opening dialog.

Upvotes: 1

Related Questions