Tips for incorporating a responsive width feature into the Drawer component in MUI v5

I'm currently working with Material UI v5 and facing a challenge in creating a responsive drawer. I want the drawer to occupy 100% of the screen width on smaller devices, while taking up only 1/3 of the screen width on larger devices. Unfortunately, I am struggling to figure out how to access the Paper property to adjust the width dynamically based on device size.

Here is my code snippet:

import { Drawer, styled } from "@mui/material";

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%", // THIS ONLY CHANGES DRAWER WIDTH NOT PAPER WIDTH INSIDE THE DRAWER
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
  },
}));

export { ResponsiveDrawer };

This is how I implement it:

import { ResponsiveDrawer } from "./Style";

<ResponsiveDrawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
        >
            ...
</ResponsiveDrawer>

Answer №1

After I posted the question, I quickly figured out the solution. It involves using inline styling with the useMediaQuery function.

const largeScreen = useMediaQuery(theme.breakpoints.up("sm"))

<Drawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
            PaperProps={largeScreen ? {
                sx: {
                    width: 450,
                }
            } : {
                sx: {
                    width: "100%",
                }
            }
            }
        >
            <CartContent cart={cart} drawer={drawer}/>
        </Drawer>

Answer №2

To customize the width of a div inside the <Drawer> or <SwipeableDrawer> component, you can simply add the following structure and use CSS (or emotion/styled) to control the width according to your preferences.

<Drawer ...>
  <div className="custom-container">...</div>
</Drawer>
.custom-container {
  width: 95vw; // ideal for mobile devices

  /* Add media queries for other screen sizes here */
}

Answer №3

The documentation provided a code snippet demonstrating how to manipulate the paper CSS within a drawer component to customize its width:

const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })(
  ({ theme, open }) => ({
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    ...(open && {
      ...openedMixin(theme),
      '& .MuiDrawer-paper': openedMixin(theme),
    }),
    ...(!open && {
      ...closedMixin(theme),
      '& .MuiDrawer-paper': closedMixin(theme),
    }),
  }),
);

The same mixin was applied to '& .MuiDrawer-paper' in the main drawer CSS for consistency.

To ensure responsiveness, the paper selector should be included in the styled CSS of the responsive drawer, adjusting its width based on breakpoints:

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%",
    '& .MuiDrawer-paper': {
      width: "33%",
    },
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
    '& .MuiDrawer-paper': {
      width: "100%",
    },
  },
}));

For further details on customizing nested elements, reference the following link: https://mui.com/material-ui/customization/how-to-customize/#the-sx-prop.

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

Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split ...

Caution: The minSize property is obsolete and is scheduled for removal in the upcoming major update

Recently, while working with React.js, I encountered a warning message that said the following: The minSize prop is deprecated and will be removed in the next major release. Even after conducting some research, I couldn't locate where exactly I am u ...

Are you experiencing a strange problem with the CSS button when hovering, clicking, or with the border?

Check out the code for this implementation on jsfiddle: https://jsfiddle.net/xuhang1128/cmkbu07s/2/ I utilized React and React-bootstrap to create it. .design2-statusMonitor { margin-top: 20px; .list-group-item { display: inline-block; ...

Steps for uploading an item to an API using an Excel document

I'm facing an issue where I am trying to send a large object along with an Excel file to an API. However, only my photo is being recognized and the object is not sent, resulting in an [object Object] error. I understand that this error occurs due to i ...

How to position a Bootstrap 4 button group at the bottom of a flexbox container

I am working with HTML code that looks like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="border d-flex align-items-baseline m-2 p-2" style="width: 400px"> < ...

The MUI Select component does not support using a Fragment as a child. Please consider using an array instead

I encountered some console errors while working with this react function component, specifically receiving the following error message: The MUI Select component does not accept a Fragment as a child. It is recommended to provide an array instead. functi ...

HTML - Centered layout with a constant header and footer

Imagine a layout where there is always a header at the top, a footer at the bottom, and the space between them should be filled by the content 100% (image 2). Additionally, everything in the header, content, and footer should be horizontally centered, usin ...

Focusing on a specific input category inside a div container

Struggling to customize the appearance of the last input type within the Jetpack plugin in WordPress. I have experimented with the following CSS: #subscribe-submit > input[type="submit"]::last-of-type { #subscribe-submit > input[type="submit"]:nth- ...

Tips for resolving CORS error when using mailchimp API?

Struggling with CORS error when using the Mailchimp API? Here's my code snippet using the Mailchimp package: import mailchimp from '@mailchimp/mailchimp_marketing' mailchimp.setConfig({ apiKey: process.env.NEXT_PUBLIC_MAILCHIMP_API_ ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...

Error encountered while attempting to access API with REACT, NODE, and EXPRESS

I'm encountering errors: localhost/:1 Failed to load http://localhost:5000/api/hello: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ...

Customizing the input field to have a width of 100%

Could someone provide a solution, like a link or working example, for creating input fields with rounded corners that have a width of 100% and a customizable right border? Here is the current structure I am using: <span class="rounded left-corner" ...

Chrome: Box-shadow not visible on images with a background present

Recently, I have noticed an issue with the box-shadow not displaying on images with a background on my website. This problem started occurring in Chrome a few months ago, despite working perfectly fine around six months ago. To pinpoint the problem, I cre ...

React Hooks state consistently lags behind

I am facing an issue with resetting the page to 1. When I use handleSearchClick function and call setPage(1), it seems to reset one click late. Therefore, after the second click, the page resets to 1. This is my current code: const [page, setPage] = R ...

Hiding the overflow conceals the entire image in one direction, while leaving the other exposed

Here is the code I have written for my project (view fiddle here): img { width: 200px; height: 200px; } .image-container { width: 600px; height: 200px; overflow: hidden; } I am working with multiple images, all sized at 200px by 200p ...

Is it possible to connect ng-model with a style tag?

Is it feasible to create a basic template editor using angularjs where an input field with an ng-model can be connected to a style tag to control the css on an entire page rather than applying it to a specific element with inline styling? Could something ...

By utilizing the <tr> element, one can enhance the border thickness by 1 pixel

Is it possible to ensure that row selection in a table is consistent in terms of border alignment on both sides? https://i.stack.imgur.com/qmZiQ.png If you have any suggestions or solutions, please share them. Thank you! table { margin: 10px; bord ...

Unable to append Jquery attribute to a div component

My code snippet is creating a div with specific classes and elements: '<div class="ctrl-info-panel col-md-12 col-centered">'+ '<h2>You do not have any projects created at the moment.</h2>'+ '<div id="t ...

The error message "document is not defined in mapbox nextjs" indicates that there is an

Having trouble with the @mapbox/search-js-react package for autocompletion in my Next.js project. I keep getting an error saying "document is not defined." I attempted: { typeof window !== "undefined" && <PlacesSuggest /> } But it's still ...

Does anyone know if it's achievable to include a background position within the img /asp:image tag?

Currently, I am endeavoring to enhance the loading speed of my webpage. The initial approach I decided to pursue is base64 conversion. On my homepage, there are a total of 18 small images that need to be loaded. Since base64 encoding increases image size ...