How to create a navbar using Material-UI in React

Material UI is an open-source library that implements Google’s Material Design providing beautifully styled and customizable React components. Among these, the AppBar component is an excellent choice for creating a sleek and efficient navigation bar in our existing React project.

Prerequisites

To start creating a navigation bar, we need a React application with Material UI installed.

Note: To get a better experience while viewing the navigation bar in the code widgets presented below, please click on the link followed by Your app can be found at link:.

Add the AppBar component

Please click the "Run" button to view a simple and non-functional AppBar component.

import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';

function App () {

    return (
      <AppBar position="static">
        <Toolbar>
        </Toolbar>
      </AppBar>
    );
  }
export default App;
Adding AppBar and ToolBar components in React application

Code explanation

  • Lines 2–3: We import the AppBar and the ToolBar components from @mui/material/AppBar and @mui/material/ToolBar, respectively.

Note: ToolBar is used to create a horizontal bar layout to align items such as buttons, text, and icons.

AppBar is used to create a responsive navigation bar at the top of the page.

  • Line 8: We create the AppBar component with the position propIt is argument/value/attribute that the component takes. The position prop helps us define how our navigation bar should behave on scrolling.

  • Line 9: We create the ToolBar component that helps us align the navigation bar's contents in a horizontal layout. In the coming sections, we will define all functionalities and components in the ToolBar.

Add the logo and text in the AppBar

Please click the "Run" button to view the logo and text added in the AppBar component.

import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import StoreIcon from '@mui/icons-material/Store';
import Typography from '@mui/material/Typography';

function App() {

    return (
      <AppBar position="static">
        <Toolbar>
          <StoreIcon></StoreIcon>
            <Typography
              variant="h5"
              noWrap
              component="a"
              href="/"
              sx={{
                mr: 2,
                fontWeight: 200,
                fontFamily:'roboto',
                color:'white',
                letterSpacing: '.2rem',
                textDecoration: 'none',
              }}
            >
              Educative
            </Typography>
        </Toolbar>
      </AppBar>
    );
  }
export default App;
Adding logo and text in AppBar component

Code explanation

  • Line 4: We import StoreIcon from @mui/icons-material/Store.

Material UI provides us with a collection of icons that we can get from this link.

  • Line 5: We import Typography from @mui/material/Typography.

  • Line 12: We create the StoreIcon component, which will display a store icon.

  • Lines 13–26: We create the Typography component to display text. We use the following props in it:

    • variant: Defines the type of text to be displayed. The options are h1, h2, h3, h4, h5, etc.

    • noWrap: Defines that the text should not span to the next line.

    • component: Defines that the component should be displayed as an anchor or link.

    • sx: Defines the styles to be applied to the text.

  • Line 27: We write Educative as the text to be displayed. We can customize the text according to our use case.

Add pages in the AppBar

Primarily, we use a navigation bar to create a link between pages. In this section, we will add pages to our navigation bar. To view the pages added, please click the "Run" button below.

import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import StoreIcon from '@mui/icons-material/Store';
import Typography from '@mui/material/Typography';
import { Box, Button } from '@mui/material';


function App() {

    const my_pages = [ 'Solutions' , 'Products', 'Pricing'];
    return (
      <AppBar position="static">
        <Toolbar>
          <StoreIcon></StoreIcon>
            <Typography
              variant="h5"
              noWrap
              component="a"
              href="/"
              sx={{
                mr: 2,
                fontWeight: 200,
                fontFamily:'roboto',
                color:'white',
                letterSpacing: '.2rem',
                textDecoration: 'none',
              }}
            >
              Educative
            </Typography>
            <Box sx={{ flexGrow: 1 , display: 'flex'}}>
              {my_pages.map((page) => (
                <Button
                  key={my_pages}
                  sx={{ my: 3, color: 'white', display: 'block' }}
                >
                  {page}
                </Button>
              ))}
            </Box>
        </Toolbar>
      </AppBar>
    );
  }
export default App;
Adding pages to the navigation bar

Code explanation

  • Line 6: We import the Box and Button components from @mui/material.

  • Line 11: We create an array, my_pages, which contains the name of pages to include in the navigation bar.

  • Lines 32–41: We create a Box component containing a loop that iterates through the my_pages array and renders a Button component for each array item.

Add settings in the AppBar

We come across websites with settings options in the top right corner of the page. In this section, we will see how we can add settings to our AppBar component. To view the settings option, please click the "Run" button below.

import React, { useState } from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import StoreIcon from '@mui/icons-material/Store';
import Typography from '@mui/material/Typography';
import { Box, Button } from '@mui/material';
import Avatar from '@mui/material/Avatar';
import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import Menu from '@mui/material/Menu';


function App() {
    const my_pages = [ 'Solutions' , 'Products', 'Pricing'];
    const my_settings = ['Profile', 'Account','Logout'];

    const [anchorElUser, setAnchorElUser] = useState(null);

    const handleOpenSettingsMenu = (event) => {
      setAnchorElUser(event.currentTarget);
    };

    const handleCloseSettingsMenu = () => {
      setAnchorElUser(null);
    };


    return (
      <AppBar position="static">
        <Toolbar>
          <StoreIcon></StoreIcon>
            <Typography
              variant="h5"
              noWrap
              component="a"
              href="/"
              sx={{
                mr: 2,
                fontWeight: 200,
                fontFamily:'roboto',
                color:'white',
                letterSpacing: '.2rem',
                textDecoration: 'none',
              }}
            >
              Educative
            </Typography>
            <Box sx={{flexWrap:'wrap',flexGrow: 1, display:'flex' }}>
              {my_pages.map((page) => (
                <Button
                  key={my_pages}
                  sx={{ my: 2, color: 'white', display: 'block' }}
                >
                  {page}
                </Button>
              ))}
            </Box>
            <Box sx={{ flexGrow: 0 }}>
              <Tooltip title="Open my_settings">
                <IconButton onClick={handleOpenSettingsMenu} sx={{ p: 0 }}>
                  <Avatar alt="Remy Sharp" src="/static/images/avatar/2.jpg" />
                </IconButton>
              </Tooltip>
              <Menu
                sx={{ mt: '55px' }}
                id="menu-appbar"
                anchorEl={anchorElUser}
                anchorOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                open={Boolean(anchorElUser)}
                onClose={handleCloseSettingsMenu}
              >
                {my_settings.map((setting) => (
                  <MenuItem key={setting} onClick={handleCloseSettingsMenu}>
                    <Typography textAlign="center">{setting}</Typography>
                  </MenuItem>
                ))}
              </Menu>
            </Box>
        </Toolbar>
      </AppBar>
    );
}
export default App
Adding settings to the navigation bar

Code explanation

  • Lines 7–11: We import the required components to create the settings option.

  • Line 16: We create the settings array, my_settings which contains the setting items we want to add to our settings option.

  • Line 18: We create a useState variable, anchorElUser, that stores the state of the menu.

  • Lines 20–26: We define the handleOpenSettingsMenu and the handleCloseSettinsMenu that controls whether the setting items should be displayed on the screen.

  • Lines 59–82: We create the Box component that contains the Avatar component to be displayed on the screen. We define the onClick function inside the IconButton that executes the handlOpenSettingsMenu function and toggles settings on the screen. The Menu component contains a loop that iterates through the my_settings array and renders the MenuItem components.

Conclusion

In this way, we can create a navigation bar in our React application by leveraging the AppBar component provided by Material UI.

Copyright ©2024 Educative, Inc. All rights reserved