React

Create a Responsive Navbar using ReactJS

In the world of web development, creating a user-friendly and aesthetically pleasing navigation bar is a crucial aspect of designing any website...

Written by Shivangi Rajde · 3 min read >
Responsive navbar using react

In the world of web development, creating a user-friendly and aesthetically pleasing navigation bar is a crucial aspect of designing any website or web application. Fortunately, with the power of ReactJS and the elegant components provided by Material-UI, crafting a responsive navbar has never been easier. In this tutorial, we’ll walk you through the process of building a responsive navbar using Material-UI in a ReactJS project named “material-ui-demo.” By the end of this guide, you’ll have a fully functional and adaptable navigation bar that will enhance the user experience of your web application.

Why ReactJS?

ReactJS is a powerful library for building user interfaces, known for its component-based architecture and virtual DOM. Leveraging ReactJS to create a responsive navbar allows us to modularize our code, making it easier to maintain and scale. Additionally, React’s reactivity enables dynamic updates to the navbar without requiring a page refresh.

Let’s dive into the steps to create a responsive navbar in ReactJS.

Set Up Your React Project

Before we start coding, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can create a new React project using the Create React App tool:

npx create-react-app material-ui-demo
cd material-ui-demo
npm start

This will initialize a new React project and start a development server.

Create the Navbar Component

Inside the src folder, create a new file named Navbar.js. This file will contain our responsive navbar component. You can directly use this code or structure it like this and make the modifications as per your requirement:

import React from "react";
import { NavLink as Link } from "react-router-dom";
import {
  AppBar,
  Box,
  Toolbar,
  IconButton,
  Typography,
  Menu,
  Container,
  Avatar,
  Button,
  Tooltip,
  MenuItem,
} from "@mui/material";
import MenuIcon from "@mui/icons-material/Menu";
import FilterVintageIcon from "@mui/icons-material/FilterVintage";

const Navbar = () => {
  const pages = ["RegistrationForm", "TypographyComponent"];
  const settings = ["Profile", "Account", "Dashboard", "Logout"];

  const [anchorElNav, setAnchorElNav] = React.useState(null);
  const [anchorElUser, setAnchorElUser] = React.useState(null);

  const handleOpenNavMenu = (event) => {
    setAnchorElNav(event.currentTarget);
  };
  const handleOpenUserMenu = (event) => {
    setAnchorElUser(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

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

  return (
    <div>
      <AppBar position="static">
        <Container maxWidth="xl">
          <Toolbar disableGutters>
            <Link to="/">
              <FilterVintageIcon
                sx={{ display: { xs: "none", md: "flex" }, mr: 1 }}
              />
              <Typography
                variant="h6"
                noWrap
                component="a"
                href="/"
                sx={{
                  mr: 2,
                  display: { xs: "none", md: "flex" },
                  fontFamily: "monospace",
                  fontWeight: 700,
                  letterSpacing: ".3rem",
                  color: "inherit",
                  textDecoration: "none",
                }}
              ></Typography>
            </Link>
            <Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
              <IconButton
                size="large"
                aria-label="account of current user"
                aria-controls="menu-appbar"
                aria-haspopup="true"
                onClick={handleOpenNavMenu}
                color="inherit"
              >
                <MenuIcon />
              </IconButton>
              <Menu
                id="menu-appbar"
                anchorEl={anchorElNav}
                anchorOrigin={{
                  vertical: "bottom",
                  horizontal: "left",
                }}
                keepMounted
                transformOrigin={{
                  vertical: "top",
                  horizontal: "left",
                }}
                open={Boolean(anchorElNav)}
                onClose={handleCloseNavMenu}
                sx={{
                  display: { xs: "block", md: "none" },
                }}
              >
                {pages.map((page) => (
                  <MenuItem key={page} onClick={handleCloseNavMenu}>
                    <Link to={page}>
                      <Typography textAlign="center">{page}</Typography>
                    </Link>
                  </MenuItem>
                ))}
              </Menu>
            </Box>
            <Link to="/">
              <FilterVintageIcon
                sx={{ display: { xs: "flex", md: "none" }, mr: 1 }}
              />
              <Typography
                variant="h5"
                noWrap
                component="a"
                href="/"
                sx={{
                  mr: 2,
                  display: { xs: "flex", md: "none" },
                  flexGrow: 1,
                  fontFamily: "monospace",
                  fontWeight: 700,
                  letterSpacing: ".3rem",
                  color: "inherit",
                  textDecoration: "none",
                }}
              ></Typography>
            </Link>
            <Box sx={{ flexGrow: 1, display: { xs: "none", md: "flex" } }}>
              {pages.map((page) => (
                <Button
                  key={page}
                  onClick={handleCloseNavMenu}
                  sx={{ my: 2, color: "white", display: "block" }}
                >
                  <Link to={page}>{page}</Link>
                </Button>
              ))}
            </Box>

            <Box sx={{ flexGrow: 0 }}>
              <Tooltip title="Open settings">
                <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                  <Avatar alt="Remy Sharp" src="/static/images/avatar/2.jpg" />
                </IconButton>
              </Tooltip>
              <Menu
                sx={{ mt: "45px" }}
                id="menu-appbar"
                anchorEl={anchorElUser}
                anchorOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                keepMounted
                transformOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                open={Boolean(anchorElUser)}
                onClose={handleCloseUserMenu}
              >
                {settings.map((setting) => (
                  <MenuItem key={setting} onClick={handleCloseUserMenu}>
                    <Typography textAlign="center">{setting}</Typography>
                  </MenuItem>
                ))}
              </Menu>
            </Box>
          </Toolbar>
        </Container>
      </AppBar>
    </div>
  );
};

export default Navbar;

This code defines a simple responsive navbar with a menu icon for mobile devices. The output would look as shown below:

Responsive Nav bar demo
Responsive Nav bar demo

Include the Navbar in App.js

Open src/App.js and import the Navbar component we just created. We have also added the Routes and Route components here from react-router-dom as we need the Appbar links to work and take us to the respective pages.

…
<div className="App">
        <Navbar />
        <Routes>
          <Route path="/" />
          <Route path="/RegistrationForm" element={<RegistrationForm />} />
          <Route
            path="/TypographyComponent"
            element={<TypographyComponent />}
          />
        </Routes>
</div>
…

The BrowserRouter component is imported from the react-router-dom package. This package provides routing functionality for React applications.

The Routes component is used to define the different routes in the application. In this case, there are three routes: the home page, the registration form page, and the typography component page.

The Route component is used to define a single route. The path prop specifies the URL path for the route, and the element prop specifies the React component that should be rendered for that route.

The App component returns a Router component that contains a div element with the class name App. The div element contains the Navbar component, the Routes component, the RegistrationFrom component, and the TypographyComponent component.

When the App component is rendered, the Navbar component will be rendered first. The Routes component will then be rendered, which will render the appropriate React component based on the current URL path.

Start the Development Server

Finally, start your development server by running:

npm start

Visit http://localhost:3000 in your web browser, and you should see your Material-UI responsive navbar in action!

Conclusion

In this article, we’ve provided a detailed, step-by-step guide on how to set up a React application with a navigation bar using popular libraries like material-ui and react-router-dom. By following these instructions, you can create a well-structured and styled navigation bar that can serve as the backbone of your web application. With this foundation in place, you’re well-equipped to expand your project by adding more pages and customizing the design to match your specific requirements.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *