Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attribute.

To address this, I changed it to transform: translate(350px, 0px), but then encountered another problem where clicking the button does not show the drawer. Any suggestions on how to resolve this?

I found a solution and made changes to the code.

Check out the demo here => View Demo

Provided below is the code:

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>
      <div>
        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer 
                  open={this.state.openDrawer}
                  containerClassName={!this.state.openDrawer? "hide-drawer": "show-drawer" }
                  openSecondary={true}
                  docked={true} 
                >
                    <div className="drawer-title-div">
                        <h4 className="drawer-title-text">It's my drawer</h4>
                    </div>
                </Drawer>
      </div>
      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

style.css

h1, p {


font-family: Lato;
}

.show-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(0%, 0px) !important;
}

.hide-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(100%, 0px) !important;
}

/* .drawer-side-drawer:focus {
  top: 47px !important;
  text-align: left !important;
  width: 350px !important;
  transform: translate(0px, 0px) !important;
} */

.drawer-title-div {
  display: inline-block;
  width: 100%;
  background: #F2F8FB;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,0.24);
}

.drawer-title-text {
  display: inline-block;
  margin-left: 16px;
  margin-top: 16px;
  margin-bottom: 16px;
  color: #484848;
  font-family: Muli;
  font-size: 16px;
  font-weight: 600;
}

Answer №1

In order to implement mui version 5, the use of PaperProps prop is required as shown below:

        <Drawer
          PaperProps={{
            sx: { width: "90%" },
          }}
        >{...Child elements here}</Drawer>

Answer №2

Here is a quick snippet you can include in your index.css file:

.MuiDrawer-paper {
width: 60% !important;
}

@media (max-width: 1200px) {
    .MuiDrawer-paper {
 width: 100% !important;
 }
}

Answer №3

To enhance the width of your MUI Drawer, simply include

PaperProps={{ style: { width: '25%' } }}
in your code.

This should successfully adjust the width for all users.

Answer №4

To simplify your code, consider implementing a toggle class instead of using the transform property.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>
      <div>
        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer containerClassName={!this.state.openDrawer ? "hide-drawer": "show-drawer"} 
                  open={this.state.openDrawer}
                  openSecondary={true}
                  docked={true} 
                >
                    <div className="drawer-title-div">
                        <h4 className="drawer-title-text">It's my drawer</h4>
                    </div>
                </Drawer>
      </div>
      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

Answer №5

To find a solution to this problem, consider retrieving the width of the parent element:

const parentElement = useRef<HTMLDivElement>(null);

 <Container
  ref={parentElement}
 >
  <Drawer
    PaperProps={{
      sx: {
        width: parentElement?.current?.clientWidth || 0,
      },
    }}
  >
    // add your content here
  </Drawer>
</Container>

Answer №6

Explore Drawer Component in Material-UI By clicking on the link provided, you can access information regarding the properties of the Drawer component.

width (union: string number) [default : null] The width of the Drawer can be specified in pixels or percentage using a string format such as 50% to fill half of the window or 100%. By default, it utilizes theme values.

To adjust the Drawer width, simply update the tag with the desired width value,

<Drawer width="50%"></Drawer>

You can test it out here.

The mismatch between the drawer width and the theme drawer width was causing the issue, not the transform CSS attribute.

A different approach:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Responsive from 'react-responsive-decorator'; // This decorator allows using the library as a decorator.

@Responsive
class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false,
      width:350
    };

  }
  // Update for media query adjustment
  componentDidMount() {
    this.props.media({ minWidth: 768 }, () => {
      this.setState({
        width: 350
      });
    });
  this.props.media({ maxWidth: 768 }, () => {
      this.setState({
        width: 150
      });
    });
  }
  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>
      <div>
        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer width={this.state.width} //<- Update
                  open={this.state.openDrawer}
                  containerClassName="drawer-side-drawer"
                  openSecondary={true}
                  docked={true} 
                >
                    <div className="drawer-title-div">
                        <h4 className="drawer-title-text">It's my drawer</h4>
                    </div>
                </Drawer>
      </div>
      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

Answer №7

Utilize the window.innerWidth property with width: 100%:

<Drawer ...>
    <div style={{width: window.innerWidth * 0.25}}>
        ...
    </div>
</Drawer>

Answer №8

Encountered a similar issue.

Simply include the PaperProps in your drawer component.

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

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Is it necessary to execute `npx rnx-dep-check --init library` separately for each library within your project when using rnx-kit?

Currently, I'm following the instructions found in the manual for rnx-kit. In the Onboarding portion, it suggests creating the dependency manager configuration for your package by utilizing npx rnx-dep-check --init library. I have 20 packages listed i ...

Retrieve data from a JSON object and assign it to a variable in JavaScript

I'm currently working on implementing AJAX to send and receive data in Django. My model consists of three fields: id, parent, and text. However, when attempting to post the information back to Django, I encounter an error due to additional fields pre ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

When submitting, Redux objects are being submitted with empty values

Whenever I try to submit my form, the object is being submitted empty. This was confirmed using the redux dev-tool, where it shows that the object is empty upon submission. The expected behavior is for a card to appear on the DOM with the information enter ...

Identify dead hyperlinks on a webpage with the help of selenium webdriver while steering clear of links that

I have been trying to identify broken links on a webpage by extracting all anchor tags. However, some of the links are dynamically generated through JavaScript. When I attempt to print out the list of all the links, I encounter a StaleElementReferenceExcep ...

Add a new string to a class within a Vue.js component

Hey there, currently working on a Vue component where I am iterating through a list of countries. Here's how it looks: <div v-for="i in countries" :key="i.id"> {{i.name}} <span class="flag-icon-gr"></span> I want to dynamically ...

How can we control the content being displayed on our tree?

Is there a way to customize the view of our V-treeview by filtering what is displayed? By entering the beginning of an element key in the filter field input, the tree will only show elements whose keys match the input. I am working on Vue.js with the late ...

The time.js library is providing inaccurate second values for the given date and time

Utilizing the moment.js library along with the Timezone and BusinessDays extensions in Vue.js, I am developing a datetime format for storing in a MySQL database. Here is the code snippet: import moment from 'moment-timezone' ...

Guide on linking an id with a trigger function in HTML and JavaScript

In the snippet below, I aim to create a responsive feature based on user input of 'mute' and 'muteon'. Whenever one of these is entered into the textbox, it will change the color of linked elements with the IDs "text" and "text1" to red ...

Style Vue slots one by one

I am a beginner delving into the world of vue (specifically, vue 2) and aiming to grasp the concept of utilizing slots in the most effective manner. Below is the code I'm working with: <template> <div> <button cla ...

Develop a custom chat feature in HTML with the powerful VueJs framework

Currently, I've been developing a chat plugin for HTML using VueJs. My dilemma lies in creating a versatile plugin that can seamlessly integrate into any website. My ultimate goal is to design a plugin that can be easily deployed on various websites ...

Having trouble with Tailwind CSS not functioning correctly once the font is imported?

I am currently working on a next.js project and utilizing tailwind for styling. I have noticed an odd behavior when importing a custom font into my globals.css file. page.jsx "use client"; import React from "react"; const page = () = ...

Once an ng-repeat is completed, I must extract and retrieve the 'id' of a specific element

Is it possible to retrieve the 'id' of the comment I'm replying to and save it for an Ajax call? I can easily access other data with ng-model, but using value="{{this.id}}" in a hidden input doesn't seem to work like in JQuery. <scr ...

The specified 'detail' property cannot be found on the given type '{}'. Error code: 2339

I encountered the error mentioned in the title while working on the code below. Any suggestions on how to resolve this issue? Any assistance would be greatly appreciated! import { useHistory } from "react-router-dom"; let h ...

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...

When attempting to add a new row to a table, the function fails to function properly

I am facing an issue with my dynamic HTML table. Each row in the table should have two cells whose values are multiplied together. I have created a function to achieve this, but it only works on the first row of the table and not on any new rows added by c ...

Integrate ThreeJs models into an Angular JS application

I have a question that pertains to my webapp development. I am currently utilizing Angular Js (v1.5/1.6) and I would like to incorporate some minimalistic 3D animated models by integrating Three Js. Although I have attempted to configure certain aspects, ...

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...

Making all requests server-side in Next.JS: A step-by-step guide

I am in the process of creating a Next.JS application that will be retrieving data from both a Python API and a Postgres Database. Although this task may seem straightforward, the project requirements dictate that all requests must originate from the serv ...