In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the drawer's width decreases to 240px.

The problem occurs when the screen is larger than 600px: when the drawer is open, the page's scrollbar disappears, rendering the page unscrollable. Conversely, when the drawer is closed, the scrollbar reappears, allowing for scrolling.

To address this concern, the objective is to ensure that the scrollbar remains visible even when the drawer is opened.

Everything operates smoothly when the width is equal to or less than 600px.

To explore the code sandbox, visit this link: code sandbox


const drawerWidth = 240;
const transitionDuration = 1000; //alternative: can also leverage theme.transitions.duration

const useStyles = makeStyles(() => {
  return {
    menuButton: {
      marginRight: (theme) => theme.spacing(2)
    },
    hide: {
      display: "none"
    },
    appBar: {
      zIndex: (theme) => `${theme.zIndex.drawer + 1} !important`
    },
    drawer: {
      width: (theme) => theme.drawerWidth,
      "& .MuiBackdrop-root": {
        display: "none"
      }
    },
    drawerPaper: {
      width: (theme) => theme.drawerWidth,
      backgroundColor: "rgba(120, 120, 120, 0.2)"
    },
    content: {
      padding: (theme) => theme.spacing(3),
      transition: (theme) =>
        theme.transitions.create("margin", {
          easing: theme.transitions.easing.easeOut,
          duration: transitionDuration
        }),
      minWidth: (theme) => theme.drawerWidth,
      marginLeft: (theme) => 0
    },
    contentShift: {
      transition: (theme) =>
        theme.transitions.create("margin", {
          easing: theme.transitions.easing.easeOut,
          duration: transitionDuration
        }),
      minWidth: (theme) => theme.drawerWidth,
      marginLeft: (theme) => theme.drawerWidth
    }
  };
});

export default function App() {
  const theme = useTheme();
  const greaterThan375 = useMediaQuery("(min-width:600px)");
  theme.drawerWidth = greaterThan375 ? drawerWidth : "100%";
  const classes = useStyles(theme);
  const [open, setOpen] = React.useState(greaterThan375);

  useEffect(() => {
    setOpen(greaterThan375);
  }, [greaterThan375]);

  const handleMenuClick = () => {
    setOpen(!open);
  };

  return (
    <div>
      {/*fixed is default */}
      <AppBar position="fixed" className={classes.appBar}>
        <Toolbar>
          <IconButton //hide on desktop
            color="inherit"
            onClick={handleMenuClick}
            edge="start"
            className={clsx(classes.menuButton, greaterThan375 && classes.hide)}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap>
            Responsive Drawer
          </Typography>
        </Toolbar>
      </AppBar>
      <Drawer
        //add full width for responsive
        className={classes.drawer}
        variant="temporary"
        //elevation={3} only works with variant="temporary"
        open={open}
        transitionDuration={{
          enter: transitionDuration,
          exit: transitionDuration
        }}
        classes={{
          paper: classes.drawerPaper
        }}
        PaperProps={{ elevation: 9 }}
      >
        <Toolbar />
        <div>
          <List>
            {["Home", "Page 1", "Page 2", "Page 3"].map((text, index) => (
              <ListItem button key={text}>
                <ListItemIcon>
                  <AppsIcon />
                </ListItemIcon>
                <ListItemText primary={text} />
              </ListItem>
            ))}
          </List>
        </div>
      </Drawer>
      <main className={clsx(classes.content, { [classes.contentShift]: open })}>
        <Toolbar />
        <Typography>
          Dummy text for demonstration purposes.
        </Typography>
      </main>
    </div>
  );
}


Answer №1

Underneath the surface, the Drawer component utilizes a Modal. Within the Drawer component, there is a property called ModalProps where you can specify additional props for the Modal. To prevent scrolling locking in this scenario, make sure to set the disableScrollLock flag on the Modal.

      <Drawer
        // ...
        ModalProps={{ disableScrollLock: true }}
      >
        // ...
      </Drawer>

Answer №2

The issue was resolved by switching the drawers variant from temporary to persistent.

<Drawer
      //add full width for responsive
        className={classes.drawer}
        variant="persistent"
        //elevation={3} only works with variant="temporary"
        open={open}
        transitionDuration={{
          enter: transitionDuration,
          exit: transitionDuration
        }}
        classes={{
          paper: classes.drawerPaper
        }}
        // PaperProps={{ elevation: 9 }}
      >
        <Toolbar/>
        <div>
          <List>
            {["Home", "Page 1", "Page 2", "Page 3"].map((text, index) => (
              <ListItem button key={text}>
                <ListItemIcon>
                  <AppsIcon />
                </ListItemIcon>
                <ListItemText primary={text} />
              </ListItem>
            ))}
          </List>
        </div>
      </Drawer>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CORS - Preflight request response fails access control verification

I've been attempting to send a GET request to a server with the same domain as my local host, but I keep encountering the following error: The preflight request response fails the access control check: The requested resource does not have an ' ...

Creating an external JavaScript and CSS file for date picker in Eclipse can be done by following a few simple steps. By creating separate files for the

I am using the following javascript and css styles: <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jq ...

Implementing JSON response in email functionality using Ajax and PHP

I've encountered a problem with my contact form. I'm receiving error messages for invalid email and incomplete fields, but I'm not getting a success message. As a result, the email is being sent twice without any confirmation message (I&apos ...

The directives applied within ng-include are not functioning correctly

Below is a custom directive I have implemented. var fancySelectDirective = pluginDirecitvesModule.directive("custom-select",function(){ return { restrict: 'C', link: function (scope, element, attrs) { ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

What is the best way to get rid of the highlighted focus in the React material-ui Tab Component

I am currently using a Tab component from the react Material-ui library, and I have noticed that when the Tab element is in focus, it displays a strange outline on the left and right borders. Is there a way to remove this active/focus outline? Check out ...

CSS problem causing issues with block display in basic gallery

I've created this code: <head> <style type="text/css"> div.img { margin: 2px; border: 1px solid #0000ff; height: auto; width: auto; float: left; text-align: center; } div.img img { display: inline; margin: 3px; border: 1 ...

Implementing jQuery getScript in a Ruby on Rails 3 application

After watching a railscast tutorial on loading records through ajax when a link is clicked, I implemented the following javascript: $(function() { $("#dash_container th a").live("click", function() { $.getScript(this.href); return false; }); } ...

Improprove the efficiency of rendering cubes in threejs

Here is the code snippet I am working with: https://github.com/CrizzzSombiii/laboratoryofsombiisbycrizz/blob/master/docs/maze2.htm <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.js"></script> <script> // Code f ...

React component displaying content while waiting for data from localStorage to load

I am facing challenges in incorporating a specific React code that retrieves and displays information from localStorage. Within my project, I have a collection of thumbnail images (components) that, upon being clicked, execute a function to fetch data fro ...

Tips for emphasizing v-list-item on click (Vue)

I am currently working on a side menu that changes based on the selected router model. My goal is to have the selected page highlighted when clicked. I would like this functionality for all the submenus as demonstrated in this example. Below are snippets ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...

Unexpected Typescript error when React component receives props

I encountered an unexpected error saying ": expected." Could it be related to how I'm setting up props for the onChange event? Here is my code for the component: import React from "react"; interface TextFieldProps { label?: string; ...

What is the best way to combine several packed props simultaneously?

After attempting the following, I encountered the following error: Unhandled Runtime Error TypeError: navbar.makeButtonClick is not a function Source .next/static/chunks/pages/index.js (19:29) @ onClick 17 | return( 18 | <button href='#&apo ...

Why is this element occupying an excessive amount of space horizontally?

I've been diligently working on a unique custom WordPress theme as part of a school project. Our task is to redesign the homepage of an association, in my case, a theater group. One of the challenges I encountered was customizing the WordPress menu t ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Transferring information using "this.$router.push" in Vue.js

I'm currently developing a restaurant review project using Django REST and Vue.js. To ensure uniqueness, I have adopted Google Place ID as the primary key for my restaurants. The project also incorporates Google Place Autocomplete functionality. The ...

Activate function on Selected DIV

Within this div, I have set the tabindex attribute to '-1' so that it can be focused on mouse click. <div tabindex='-1'></div> .div:focus{//some style} My goal is to use jQuery to perform an action when a user clicks on th ...

Creating an undo feature for a dynamically generated checklist of checkboxes

I am using a combination of javascript/jquery and html to dynamically populate the page with checkboxes. When you click "add", a new checkbox is created. I am now looking for a way to add an undo button that would delete the last checkbox created. Here is ...