Tips on making Material-UI Drawer compress other content when it is open

Seeking assistance from those familiar with CSS and Material UI! I'm currently working on implementing a Material UI Drawer component that doesn't just slide out over the top of the page content, but actually causes the page content to adjust around it by squeezing or expanding. My project utilizes Bootstrap rows and containers, but I'm unsure how to use them to achieve this effect. Here is how my component is structured:

<div>
    <AppBar
    onLeftIconButtonTouchTap={this.handleToggle}
      title="Imaginary Company"
    />
    <Row>
      <QuotesList />
    </Row>
    <Drawer
    containerStyle={{ top: 64, width:150 }}
    open={this.state.open}
    >
      <MenuItem>Menu Item</MenuItem>
      <MenuItem>Menu Item 2</MenuItem>
    </Drawer>
  </div>

The 'top' property is included to ensure the top title area of the App Bar remains visible when the drawer is open or closed. Any advice or guidance would be greatly appreciated. Thank you!

UPDATE: After some experimentation, I have come up with a solution using the 'styled-components' library. By creating a wrapper component that accepts a 'collapsed' prop and implements an animation sliding to the right equal to the drawer's width (150), I was able to achieve the desired effect. Below is the code snippet using styled-components:

const CollapsibleContainer = styled.div`
margin-left: auto;
margin-right: auto;
padding-left: 15px;
padding-right: 15px;
$:after {
content: "";
display: table;
clear: both;
}
position: absolute;
right: 0;
left: ${props => props.collapsed ? '150px' : '0'}!important;
transition: 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms;
`; 

While not a flawless solution, it serves its purpose well. Hopefully, this can be helpful to someone else facing a similar challenge. :)

Answer №1

Here is a solution similar to your "hacky" approach, with a jsFiddle link provided: https://jsfiddle.net/88uq8751/3/

The concept is the same. You shift your content to the right by the width of the drawer, applying a transition or animation effect. This can be achieved in various ways, using properties like width, marginLeft, absolute positioning, or even transform:translate. In this example, I utilized marginLeft:

const { Drawer, RaisedButton, MuiThemeProvider, getMuiTheme } = MaterialUI;

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { drawerOpen: false };
  }

  render() {
    const contentStyle = {  transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' };

    if (this.state.drawerOpen) {
      contentStyle.marginLeft = 256;
    }

    return (
      <div>
        <Drawer open={this.state.drawerOpen}>
          <div style={{ textAlign: 'right' }}>
            <RaisedButton onClick={() => this.setState({ drawerOpen: false }) }>X</RaisedButton>
          </div>
          {this.props.children}
        </Drawer>
        <div style={contentStyle}>
          <RaisedButton onClick={() => this.setState({ drawerOpen: true }) }>Open</RaisedButton>
          <p>
            Lorem ipsum dolor sit amet, amet epicuri vel ea, noster causae oporteat has ut, ad est periculis concludaturque.Mundi docendi volutpat ut sea, an sea suas epicurei.Sea numquam definitionem ne.Te postea aliquip invidunt quo.Id prima commune complectitur pri, sed at vero posse contentiones, sea cu fugit etiam iusto.Ei mei prima appareat, est brute luptatum iudicabit id.Alii homero imperdiet usu id, dico meis alienum per ad, dolorem mentitum philosophia quo id.
          </p><p>
            Nec in dolor ancillae contentiones, at harum graecis his.An delectus scripserit pro.Ei dicta liber vis, sed no quidam legimus fabellas, no expetendis vituperata mei.Vim et ferri nominavi constituto.Wisi tamquam intellegebat duo in.Omittam adolescens abhorreant no sea.Cibo iusto verear ut mea, per at viris nominavi referrentur.
          </p><p>
            Sea officiis moderatius te.Graeci causae malorum ius in, cu has offendit tractatos interpretaris.Ea porro liberavisse mei, no mei propriae salutandi intellegat, te nibh singulis vim.Vim mucius feugait blandit ea.At est mollis vivendo.Eu has choro doctus verterem.Utroque suscipiantur ne eum, vix in alia intellegat.
          </p><p>
            Lorem ipsum dolor sit amet, amet epicuri vel ea, noster causae oporteat has ut, ad est periculis concludaturque.Mundi docendi volutpat ut sea, an sea suas epicurei.Sea numquam definitionem ne.Te postea aliquip invidunt quo.Id prima commune complectitur pri, sed at vero posse contentiones, sea cu fugit etiam iusto.Ei mei prima appareat, est brute luptatum iudicabit id.Alii homero imperdiet usu id, dico meis alienum per ad, dolorem mentitum philosophia quo id.
          </p><p>
            Nec in dolor ancillae contentiones, at harum graecis his.An delectus scripserit pro.Ei dicta liber vis, sed no quidam legimus fabellas, no expetendis vituperata mei.Vim et ferri nominavi constituto.Wisi tamquam intellegebat duo in.Omittam adolescens abhorreant no sea.Cibo iusto verear ut mea, per at viris nominavi referrentur.
          </p><p>
            Sea officiis moderatius te.Graeci causae malorum ius in, cu has offendit tractatos interpretaris.Ea porro liberavisse mei, no mei propriae salutandi intellegat, te nibh singulis vim.Vim mucius feugait blandit ea.At est mollis vivendo.Eu has choro doctus verterem.Utroque suscipiantur ne eum, vix in alia intellegat.
          </p><p>
            Lorem ipsum dolor sit amet, amet epicuri vel ea, noster causae oporteat has ut, ad est periculis concludaturque.Mundi docendi volutpat ut sea, an sea suas epicurei.Sea numquam definitionem ne.Te postea aliquip invidunt quo.Id prima commune complectitur pri, sed at vero posse contentiones, sea cu fugit etiam iusto.Ei mei prima appareat, est brute luptatum iudicabit id.Alii homero imperdiet usu id, dico meis alienum per ad, dolorem mentitum philosophia quo id.
          </p><p>
            Nec in dolor ancillae contentiones, at harum graecis his.An delectus scripserit pro.Ei dicta liber vis, sed no quidam legimus fabellas, no expetendis vituperata mei.Vim et ferri nominavi constituto.Wisi tamquam intellegebat duo in.Omittam adolescens abhorreant no sea.Cibo iusto verear ut mea, per at viris nominavi referrentur.
          </p><p>
            Sea officiis moderatius te.Graeci causae malorum ius in, cu has offendit tractatos interpretaris.Ea porro liberavisse mei, no mei propriae salutandi intellegat, te nibh singulis vim.Vim mucius feugait blandit ea.At est mollis vivendo.Eu has choro doctus verterem.Utroque suscipiantur ne eum, vix in alia intellegat.
          </p>        
        </div>
    </div>
    );
  }

}

const App = () => (
  <MuiThemeProvider muiTheme={getMuiTheme() }>
    <Example />
  </MuiThemeProvider>
);

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

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

MUI Version 5: Is it necessary to have @emotion/react or @emotion/styled installed in order to utilize the sx prop?

I recently upgraded my project from version 4 to version 5, and I am exclusively using the sx prop. Despite not having installed @emotion/react, everything appears to be functioning correctly. Is there a compelling reason for me to install @emotion/react ...

Include new material in the upper-right corner of each row

Struggling with various styling techniques like pull-right, float, and row-fluid, I have come here to seek help: My goal is simple - I want a Map to be displayed on the right side of a set of rows. Currently, it looks like this: Although close to what I ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Pattern to locate a CSS class identifier

I've been working on creating a regex to match valid CSS class name structures. Currently, my progress looks like this: $pattern = "([A-Za-z]*\.[A-Za-z]+\s*{)"; $regex = preg_match_all($pattern, $html, $matches); However, there are certai ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

Having difficulty with uploading images in the correct size on the AWS S3 server

When I upload an image to AWS S3 bucket, the image size is only showing as 6 Byte, which is not the actual size of the image. I am confused why the image is not uploading with its actual size. What could be causing this issue? interest.js file Inter ...

"Troubleshooting: Issues with Next.js/React lazy loading not functioning as intended with

Hello everyone, I am a newcomer to Next.js and React. I am attempting to lazy load a component with the expectation that it will only load when it becomes visible in the user's viewport or after the page has fully rendered. Unfortunately, after debug ...

React component fails to re-render after state change

For the past two days, I've been struggling with this error and can't seem to fix it! I'm currently working on creating a weather app in React which utilizes the API. The app features a Bootstrap Navbar with a search option that allows user ...

Is MongoDB's find() method returning incorrect objects?

My current task involves running a Mongo query on the Order database to retrieve orders associated with a specific user by using their email. This process is achieved through an API, but I'm encountering difficulties as the returned object contains un ...

Incorporating HTML5 audio elements in JavaScript

I am working on a project where I need to create a grid of 16 audio files with separate links for each in HTML, CSS and JavaScript. Each box in the grid should link to a different audio file. My initial thought was to use a table to achieve this, so I cre ...

Create an interactive mechanism where one scrollbar dynamically adjusts another scrollbar and vice versa

Using the provided js-bin, how can I synchronize scrolling between the "left" div and the "right" div when using the mouse wheel? Currently, if you uncomment the code block, the scrolling behavior changes from scrolling by 100px per scroll to scrolling pi ...

Access parent component's properties by clicking on child component

I'm uncertain if my current approach is the most effective solution to my issue, so I am open to alternative methods. My goal is to access the properties of the parent component when clicking on a child component (Image). Below is the code I have imp ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

What is the correct way to import React's experimental hooks?

I am eager to explore the cutting-edge and unreleased features of React, particularly the "useEffectEvent" hook. However, I have encountered a problem while trying to import this specific feature from the React package. Whenever I attempt to import somet ...

The error message "TypeError: (0 , N.createContext) is not a function" indicates that

I'm currently in the process of developing a cutting-edge application using Next.js 14, TypeScript, and Telegram Open Network. However, I've hit a roadblock while attempting to incorporate the TONConnectUIProvider at the root of my app. Upon run ...

What is the best way to ensure that the size of a header is balanced on both margins?

I just recently began learning CSS about a week and a half ago, and I'm facing a challenge that I'm struggling to overcome. I want my webpage to have the same design as shown in this image, but despite trying various solutions, I can't seem ...

Tips for including and excluding personalized Chips from input

Just started learning React/typescript, any assistance would be greatly appreciated Custom Chip (CC.chip) is a specialized Chip UI component that can be utilized as demonstrated below. const [isOpen, setIsOpen] = useState(true); const onClose = Re ...

Discovering targeted information from object utilizing React

When using the fetch method to retrieve film data, how can I extract specific details from the returned object? I am able to access and manipulate properties like name, genre, cast, trailers, and recommendations, but I'm struggling with retrieving the ...

The function this.client.defaultMutationOptions does not exist in the react-query, pocketbase, and nextjs libraries

I am currently following a tutorial on using Pocketbase with NextJS, but the video I'm watching uses create-react-app. This means I have to make some adjustments as I go along. It has been an interesting experience, but I have hit a roadblock and my u ...