What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overlap. At the moment, I have set the width of the drawer using a variable and this setup is functioning properly. However, I now need to dynamically update the width of the drawer based on the width value of its child components.

Below is the code snippet featuring the Drawer component:

import { useState } from "react";

// Importing Material UI components
import { Box, Button, Drawer, Divider, Grid, IconButton } from "@mui/material";

// Additional Components
import DashboardHeader from "./DashboardHeader/DashboardHeader";
import LeadershipProfile from "./LeadershipProfile/LeadershipProfile";
import YourProfile from "./YourProfile/YourProfile";
import CustomIcon from "components/CustomIcon";
import icons from "enums/icons";

import { Theme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles";

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        leftSideContainer: {
            display: "contents",
            overflow: "auto",
            textAlign: "center",
        },
        drawer: {
            top: theme.spacing(9),
            "& .MuiDrawer-paper": {
                // width: "30%",
                marginTop: "72px",
                position: "absolute",
            },
        },
        drawerButton: {
            color: theme.palette.button.active.from,
            height: "14px",
        },
        // divider: {
        //     "& .MuiDivider-root": {
        //         right: 0,
        //     },
        // },
    })
);

const PaceLabsDashboard = () => {
    const classes = useStyles();

    const [isDrawerOpen, setIsDrawerOpen] = useState(true);
    const drawerContentWidth = 400;

    return (
        <Box>
            {/* Header */}
            <Box sx={{ border: "2px solid black", width: "100%", height: "72px", textAlign: "center" }}>
                <DashboardHeader />
            </Box>

            <Box sx={{ display: "flex" }}>
                {/* Right content */}
                <Box className={classes.leftSideContainer}>
                    <LeadershipProfile />

                    <IconButton size="small" aria-label="toggle-drawer" onClick={() => setIsDrawerOpen(!isDrawerOpen)}>
                        <CustomIcon
                            className={classes.drawerButton}
                            icon={isDrawerOpen ? icons.chevronRightThin : icons.chevronLeftThin}
                        />
                    </IconButton>
                </Box>

                {/* Left content */}
                <Drawer
                    anchor="right"
                    variant="persistent"
                    open={isDrawerOpen}
                    className={classes.drawer}
                    sx={{
                    ...(isDrawerOpen ? { display: "flex" } : { display: { xs: "block", sm: "none" } }),
                }}
                >
                    <Box>
                        <YourProfile />
                    </Box>
                </Drawer>
            </Box>
        </Box>
    );
};

export default PaceLabsDashboard;

Answer №1

sx={{
  display: { xs: 'block', sm: 'none' },
  '& .MuiDrawer-paper': {
    boxSizing: 'border-box',
    width: drawerWidth
  }
}}

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

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

What is the best way to create a horizontally scrolling row of squares in a mobile view using html and css?

Below is a screenshot that I have replicated in the code snippet. The code snippet contains a parent div with two rows mentioned: <div class="product-all-contents"> <div class="product-contents"> </div> <div class="product-contents" ...

Having issues with implementing CSS3 animations on my webpage

I'm having trouble implementing a bouncing mouse animation on my website. The code works perfectly on another site, but on mine, it's not functioning at all. Here is the CSS code: .mouse { display: block; margin: 0 auto; text-alig ...

Creating unique custom 404 error pages for specific sub-directories within NextJS using the App Router Structure

Having trouble with my custom 404 error page (= not-found.tsx) files. I have two of them, one within app/(paths) and another within app/(paths)/(jobs)/jobs/(cats). The issue is that the first not-found file should render when a user visits url example myap ...

Koffi organized a collection of structured arrays

I am currently using koffi 2.4.2 in a node.js application from koffi.dev and up until now, everything has been running smoothly. However, I have encountered an issue with integrating a native C++ library method that requires a parameter struct defined as f ...

Modify the text color of the sliderInput element within a Shiny application

I am attempting to change the font color of the values (1,2,3,...10) in the sliderInput() from black to white, but I am encountering difficulties. How can I connect the slider with the CSS file to achieve this? ui <- fluidPage( tags$style(type = &quo ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

Creating consistent div sizes for varying image and title lengths in bootstrap

In my angular project, I am receiving data in the form of image, title, and location. Despite my efforts to create a responsive div, I have been unsuccessful in achieving uniform sizes. <div *ngFor="let company of companies" class=" ...

Incorporating map() with data passed down as props from App.js into child components

I have React version 18.2 and I want the child component in App.js to receive data and utilize the map() function. Although the child component successfully receives the data, it is encountering an issue when trying to use map(). An error message is disp ...

The child component fails to inherit the data types provided by the parent component

I am currently working on setting up a dynamic table that will receive updates from the backend based on actions taken, which is why I need to pass the endpoint and response model. When I try to nest and pass the response type, it seems to get lost in the ...

Displaying ISO date format within a date input field using React

Currently, I am working on a project where I am editing records retrieved through an API. Within the data, there are two fields that represent dates. The format of the date data from the API is in "2021-07-30T20:34:40.545Z", whereas the input field display ...

"Launching" conduit for Observable

Is there a way to attach two pipes to an HttpClient request in order to execute functions at the beginning and end of the request? I have discovered the "finalize" operator for executing a function when the request is finished, but I am looking for an equi ...

Accessing a specific data point from a Rest Api with React JS

How can I extract the value '00000000000000000000000000000000' that comes after clusters in the links->href in a Rest Api response? [{ "analysisUnits": [ { "links": [ { "href": "http://127 ...

Angular8 Material Grid displaying headers and tiles, experiencing slight resizing issue with mat-grid-tile content

Exploring Angular8 Material: Grid Layout with Headers and Tiles Currently, I am delving into the workings of the grid system within Angular Material. I am dynamically fetching components and organizing them within a grid. While the grid list and tiles are ...

I am looking to save the session value into the search box of the appTables application by utilizing jQuery

Is there a way to save the session value in the search box of appTables by using jQuery? <?php $session = \Config\Services::session(); ?> <script type="text/javascript"> $(document).ready(function () { var searc ...

having difficulty implementing the blur effect in reactJS

Currently, I am working on developing a login page for my project. Below is the code snippet I have implemented for the functionality: import React, { useState, createRef } from "react"; import { Spinner } from "react-bootstrap"; import ...

Finding the automatically generated ID of a new document in a subcollection in Firebase Firestore Web V9, using Javascript/React

When a user clicks, I generate a new document in a subcollection associated with that user's profile. Below is the function responsible for this: // Function to create a new checkout session document in the subcollection under the user's profile ...

I am confused about why this error is appearing so unclear: npm ERR code Unknown system error -122npm ERR

My Next.js project runs perfectly on my local machine, but when I tried to run `npm install` on cpanel, I encountered some unclear errors: npm ERR! code Unknown system error -122npm ERR! syscall writenpm ERR! errno -122npm ERR! Unknown system error -122: U ...

Inadequate text alignment

Trying to create a header mockup for a website featuring branding elements like a logo and brand name. Utilizing Angular.js for the webpage development process, incorporating a URL for the logo image from an online source. Encountering alignment issues th ...

Flowing vertically and horizontally while adjusting line height within the <small> HTML tag

While working on the typography for my new website, I encountered an unusual issue with the <small> tag. It seems to be messing up the line-height, unlike other elements like heading tags and paragraphs. Here's a visual representation of the pr ...