How It Works: MUI Navigation Drawer
How to get this ↓ in 3 minutes (using Typescript in React)
When you code a dashboard in MUI, We want to give it a consistent layout with a layout component that wraps the children. In order to achieve this functionality, pass in an interface into the Layout and define the children prop.
We then make a Grid container and slap in the Grid item. We are putting the App Bar here so you want it to fill up the whole width (i.e. 12 columns). The App Bar is fixed to the top by default but you can scroll it out of view by setting it to relative .
Now you want to slap in 3 more things: the toolbar, the Icon Button, and a Menu Icon and run the app. This gives you a nice App Bar at the top with the menu icon on the left.
For the menu icon, you only want to show it in the mobile version. So you enclose the IconButton with the Hidden component and declare the property smUp, meaning it’s hidden for screen sizes of sm and above. You can play around with other breakpoints, but i personally recommend to sticking to smUp as it’s my most used breakpoint to switch between app and mobile screen sizes.
Now, if we run the code, you can see the menu icon hidden in desktop view, and visible in mobile view.
The next step now is to make the drawers. Start by making another Grid item and slap in the Drawer component, and then your custom drawer content.
Ideally you want the drawer to open after clicking the menu button, only in the mobile view. To achieve this you use a React hook, which is just a another word for creating a state. Slap the setOpen to true function into the icon button’s onClick function. The button state into the drawer’s open prop, and the setOpen to false function into the drawer’s onClose function. Also, you want to implement the same behaviour for the menu icon using the hidden component.
So far you have done the mobile screen version which kind of works, but you also want it to work for the desktop screen. Ideally you want the drawer to permanently lie there, so just do the same thing you just did, but declare the behaviour for the Hidden component to only='xs'
, which hides it in the mobile xs view. Also you want to take away the Drawer component to remove the open on click functionality.
You can see now that everything is working as it should
Finally you want to place the Layout's children in the right place. Just make one more Grid item below the current one to enclose the children props within.
Now you're done!
That’s cool and all, but if you want to make a backend in 2 lines of code, you can check our open source package EzBackend at https://www.ezbackend.io and sign up for our alpha!