React Material UI Drawer with Routes
Let’s dive into the material UI popular react framework and discuss how we can use the AppBar component with a drawer and router. For new users of material UI can be tricky to integrate this to elements in one peace. Below you can see how final effect will look like:
Let’s discuss what we can achieve with material UI. When we think about using themes and integrating styles with our component without using css files this solution is ideal. We can provide to our project ready to use theme system and build in material UI component to create fast and code which we can use in another project. There are some disadvantages to this concept like we must use strict rules how grid and styles look likes but when we spend some time in this environment we can improve our skills for the next level.
Let's create a new create-react-app project with dependencies:
npx create-react-app my-drawer
cd my-drawer
npm install @material-ui/core
npm install @material-ui/icons
npm install react-router-dom
Let’s create a basic file structure:
...
src/
components/
Appbar.js
pages/
Grid.js
Home.js
...
Here we define one component which will separate our app on pages. To do this we will integrate routes.
Let’s create our component:
Now we can discuss the more complicated part. We start from define drawerWidth and initiate BrowserHistory for our routes. Next, we add a little adjust for component styles. Next, we define Appbar which will be a response to the open and close drawers. Next, we define our drawer with routes. With the main div where we will display our content. The last part of our drawer mechanism is the AppBarInteraction function where we combine Toolbar with Drawer in one peace.
Let's see how look likes our example pages:
And the second side:
The last element of our app is App.js where we add all together:
This is it our component and CssBaseline to protect basic browser styles.
In this simple example, we can see that making changes in material UI should be done with patience because this create pretty complex code. The big thing is that we can build a base on its a template and then use it in another project.