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

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

Utilizing Vue CSS variables as inline styles

Incorporating CSS variables in my component has allowed me to dynamically set the width of a div based on computed data within the setup() setup(props) { const progressBar = PositionService.getProgressBar(props.position); const progressWidth = `${p ...

What is the reason for MUI not recognizing the custom palette?

Currently using MUI 4.12 with the type set to dark and implementing CssBaseline as suggested in other solutions, but it appears that the type is still not being applied. import {React, Fragment} from 'react' import { createTheme, ThemePr ...

To ensure that new tabs are opened directly within jQuery UI tabs, the tab should be created within the jQuery UI tabs interface

I have integrated jquery-UI to create a dynamic Tab panel. When I click on the "Add Tab" button, a new tab is created. However, the new tab does not open automatically. It only opens when clicked on. $(function() { var tabTitle = $( ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

When using the react-table library, the useState hook within a table always defaults to its initial value even if

I have set up a React application using react-table to organize and display fetched data in a table format. The table includes various buttons for interacting with the data, such as deleting entries or updating information (e.g., toggling approval status). ...

What is the process behind managing today's Google image of the day?

After coming across the javascript picture control on the Google search page, I became interested in replicating it myself. The feature zooms in on a picture when hovering over it, but I couldn't locate the HTML code they were using for it. Is there ...

All the GET request methods are functional except for the final one. I wonder if I made a mistake somewhere?

After examining all the GET request methods, it appears that only the last one is not functioning properly. Despite attempting to log something to the console, no output is being displayed. router.get('/', function(req, res) { Golf.find({Year: ...

Icon with label and border using Font Awesome

I'm looking to recreate this design using HTML and CSS: The icon I'm trying to replicate is actually from font awesome. Here's what I've accomplished so far: https://jsfiddle.net/0Lewug6p/1/ <head> <meta charset=" ...

Executing Javascript prior to Gatsby page load

Currently, I am in the process of converting an HTML template using Bootstrap 5 into a Gatsby template. While the CSS and pages are functioning as expected, I have encountered an issue with the inclusion of a main.js file within the HTML template that need ...

Ways to renew a Cognito session within an asynchronous function to ensure the return of valid credentials

After configuring my Redux store, I have a function that runs to setup Apollo: function configureApollo(store) { return new AWSAppSyncClient({ url: AppSync.graphqlEndpoint, region: AppSync.region, auth: { credentials: async () => {/ ...

The color of the Material UI button label remains unchanged even when the disabled state is toggled

When programmatically changing the "disabled" parameter of a Material UI button, the labels' color does not update on Safari (works for Chrome). To view the CodeSandbox example, click here: https://codesandbox.io/embed/material-demo-forked-8ly0d ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Is it possible to create a bot that's capable of "hosting events" using Discord.js?

I am searching for a solution to host "events" using Discord.js. After some research, I stumbled upon this. Although it seems to be exactly what I am looking for, the website does not provide any code examples to help me try and replicate its functionali ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

Angular's ng-repeat allows you to iterate over a collection and

I have 4 different product categories that I want to display in 3 separate sections using AngularJS. Is there a way to repeat ng-repeat based on the product category? Take a look at my plnkr: http://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview var produc ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

Tips for making a multi-dimensional array using jQuery

Is it possible to generate a jQuery layout by using two separate each statements as shown below? arrar [ 'aaa'=>'ccsdfccc', 'bb'=>'aaddsaaaa', '1'=>[ 'three'=>'sdsds& ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...