Search code examples
reactjsmobileresponsive-designmaterial-designmaterial-ui

Material UI - Responsive Drawer


Does anyone know how to, or know of any examples of how to create a reactive Appbar and Drawer?

It needs to be able to dynamically un-dock the drawer and hide when the browser is small and dock the drawer when larger, preferably dynamically like the Material UI site already does: https://mui.com/material-ui/react-drawer/


Solution

  • You could listen for screen size changes in componentWillMount like this, I'm sure there are better methods but this works.

    toggleOpenDrawer = () => {
        if (!this.state.mobile) {
            return;
        }
        this.setState({
            open: !this.state.open
        })
    }
    
    setSmall = () => {
        this.setState({open: false, docked: false, mobile: true})
    }
    
    setLarge = () => {
        this.setState({open: true, docked: true, mobile: false})
    }
    
    componentWillMount() {
      const mediaQuery = window.matchMedia('(min-width: 768px)');
      if (mediaQuery.matches) {
        this.setLarge()
      } else {
        this.setSmall()
      }
      mediaQuery.addListener((mq) => {
        if (mq.matches) {
          this.setLarge()
        } else {
          this.setSmall()
        }
      });
    }