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

Displaying photos locally in HTML is not supported

I've encountered an issue with my HTML code. I'm trying to load images from my local drive, and the path to the folder seems correct because I can open the images by ctrl + clicking on them. However, when I open my page using a live server or hos ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Troubleshooting homepage issues post react-scripts update for create react app

After following the instructions on how to upgrade a React project built with create-react-app, I successfully updated react-scripts from v1.1.4 to v3.4.3. However, I encountered an issue on the homepage that I'm struggling to resolve. In my previous ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Can you customize the "rem" values for individual Web Components when using Angular 2's ViewEncapsulation.Native feature?

I'm interested in creating a component with ViewEncapsulation.Native that utilizes Bootstrap 4 while others are using Bootstrap 3. Below is the component code with Bootstrap 4: import { Component, ViewEncapsulation } from '@angular/core'; i ...

Exploring the integration of react-leaflet with Nextjs: A step-by-step guide

Hello everyone, I'm currently facing an issue while trying to integrate a Leaflet map into my Next.js application. The error window is not defined keeps popping up and despite searching on stackoverflow, I haven't found a solution yet. The code ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

Issues with CSS overlays arise when attempting to display a welcome page on top of a flash component

Can anyone help with fixing the issue of my overlay being hidden behind the flash element? The blue bar with the 'Continue' button still shows up on top. I need some CSS changes to make sure that the overlay appears above everything else below it ...

Steps to dynamically adjust an element's width in CSS depending on the presence of a separate element

I have a text input box appearing on the left side with a button positioned next to it on the right. For certain pages, I want to display a checkbox next to the input box and move the button below it. Is there a way to achieve this using CSS flexbox or a ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Utilizing any folder as a static directory in Reactjs: A Step-by-Step Guide

My website is built on React and runs smoothly. However, I also maintain a blog using Wordpress. Whenever I try to integrate the blog content into my website by placing it in the blog directory, I encounter a 404 error because React manages everything ex ...

Is it possible to define a namespaced external module in TypeScript?

Currently, I am dealing with some legacy js modules that are either namespaced on window or define'd if the page is using AMD. Here's an example: // foo/bar.js (function (root, factory) { if (typeof define === "function" && define.am ...

Samsung devices exclusively showcase background in responsive design

I am encountering a major problem with my website design, specifically with its compatibility on mobile devices. To ensure its responsiveness, I have tested the design on my iPhone, iPad, and Windows Phone. Unfortunately, since I lack an Android device, I ...

Don't forget to update the CSS stylesheet whenever templates are rendered in Flask

I have developed a Flask application using HTML and external (static) CSS stylesheets. One interesting feature of the application is a checkbox that uses JavaScript to toggle between two different CSS stylesheets - one for light mode and one for dark mode. ...

The anchor tag seems to be malfunctioning within the div container

<style type="text/css> .xyz { position: absolute; top: 120px; left: 160px; z-index: -1; } #container { position: relative; overflow: visible; opacity: .3; } </style> <body> <div> <video i ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Having difficulty centering an image in HTML?

I've been struggling to get the image (logo) centered on the top bar! I've tried using align-self: center;, display:block;, but nothing seems to work. It feels like I'm missing something here! Click here for the codesandbox link to view the ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...

Is there a way to utilize an AXIOS GET response from one component in a different component?

I'm having trouble getting my answer from App.tsx, as I keep getting an error saying data.map is not a function. Can anyone offer some assistance? App.tsx import React, {useState} from 'react'; import axios from "axios"; import {g ...