How to implement responsive width for Drawer MUI v5 component?

Viewed 847

I am using Material UI v5, and am trying to make a responsive drawer where for smaller devices it will take up 100% of screen width while for larger devices it should only take 1/3 of screen width. But I have no idea how to access Paper property to modify the actual width and make it responsive.

My code:

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 };

How I use it:

import { ResponsiveDrawer } from "./Style";

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

I figured it out shortly after posting the question. This involves inline styling using useMediaQuery.

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>

You can add a div inside the <Drawer> or <SwipeableDrawer> component like so and control the width of the div through CSS (or emotion/styled, if you prefer).

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

  ... add media queries for rest of the screen sizes here
}
Related