Creating an AppBar with Drawer in React using Material-UI (Mui)
June 14, 2023 ⚊ 2 Min read ⚊ REACTTo create an AppBar with a drawer in React using Material-UI (Mui), you can follow these steps:
- Start by setting up a new React project if you haven’t already. You can use Create React App or any other preferred method.
- Install Material-UI by running the following command in your project directory:
npm install @mui/material @emotion/react @emotion/styled
- Import the necessary components from Material-UI in your React component file:
import React from 'react';
import { AppBar, Toolbar, IconButton, Typography, Drawer, List, ListItem, ListItemText } from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
- Create your component and define its state. In this example, we’ll use the useState hook to manage the state of the drawer:
const MyApp = () => {
const [openDrawer, setOpenDrawer] = React.useState(false);
const toggleDrawer = () => {
setOpenDrawer(!openDrawer);
};
// Rest of your component code
};
- Implement the AppBar component at the top of your component’s render method:
<AppBar position="static">
<Toolbar>
<IconButton edge="start" color="inherit" onClick={toggleDrawer}>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
My App
</Typography>
</Toolbar>
</AppBar>
- Add the Drawer component below the AppBar, inside the render method:
<Drawer anchor="left" open={openDrawer} onClose={toggleDrawer}>
<List>
<ListItem button>
<ListItemText primary="Item 1" />
</ListItem>
<ListItem button>
<ListItemText primary="Item 2" />
</ListItem>
<ListItem button>
<ListItemText primary="Item 3" />
</ListItem>
</List>
</Drawer>
- Finally, complete your component’s code and export it:
const MyApp = () => {
const [openDrawer, setOpenDrawer] = React.useState(false);
const toggleDrawer = () => {
setOpenDrawer(!openDrawer);
};
return (
<div>
<AppBar position="static">
<Toolbar>
<IconButton edge="start" color="inherit" onClick={toggleDrawer}>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
My App
</Typography>
</Toolbar>
</AppBar>
<Drawer anchor="left" open={openDrawer} onClose={toggleDrawer}>
<List>
<ListItem button>
<ListItemText primary="Item 1" />
</ListItem>
<ListItem button>
<ListItemText primary="Item 2" />
</ListItem>
<ListItem button>
<ListItemText primary="Item 3" />
</ListItem>
</List>
</Drawer>
{/* Rest of your component's content */}
</div>
);
};
export default MyApp;
That’s it! You now have an AppBar with a drawer in your React application using Material-UI (Mui). Customize the items inside the Drawer component as needed to fit your application’s requirements.