DEV Community

Stephanie Opala
Stephanie Opala

Posted on • Updated on

Simple responsive navigation bar | React.js

This article is a step-by-step guide on how to create a simple navigation bar using React.js, styled components for styling, and react router to handle routing.
NOTE: This article has been updated to use the latest version of react router, that is, version 6.

Table of contents

Prerequisites

To follow along, you will need to have:

  • Basic knowledge of React JS.

Setting up the React environment

In the terminal, run the following command to create a React application using Create React App.

npx create-react-app my-app
Enter fullscreen mode Exit fullscreen mode

Once the process is done, run the following command to get into the my-app folder.

cd my-app
Enter fullscreen mode Exit fullscreen mode

Installing the required dependencies

Install react-router-dom using the following command in your terminal.

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

We will use styled components for styling, therefore install it using the command below.

npm install --save styled components
Enter fullscreen mode Exit fullscreen mode

Lastly, we will need some icons for the project. For this, we will use react-icons. Install it using the command below.

npm install react-icons --save
Enter fullscreen mode Exit fullscreen mode

Once the installation of the above is done, start the React application using the following command.

npm start
Enter fullscreen mode Exit fullscreen mode

Structuring the project

Create a folder named components in the src folder.
Inside the components folder, create a another folder named Navbar.
Inside the Navbar folder, create two files named index.js and NavbarElements.js.

We will create another folder for the pages.
Go to src folder and create a folder named pages.
Inside pages create the following files.
index.js
about.js
contact.js
signin.js
signup.js

These will be the web pages on our website.

Creating the navbar component

Go to the components/Navbar/index.js file and create a functional component, Navbar.

index.js

import React from "react";

const Navbar = () => {
    return (
        <>
           <Nav>
            <NavLogo to="/">
                Logo
            </NavLogo>
            <Bars />

            <NavMenu>
                <NavLink 
                  to="/"
                  activeStyle={{ color:'black' }}
                >
                    Home
                </NavLink>
                <NavLink 
                  to="/about"
                  activeStyle={{ color: 'black' }}
                >
                    About
                </NavLink>
                <NavLink 
                  to="/contact" 
                  activeStyle={{ color: 'black' }}
                >
                    Contact
                </NavLink>
                <NavLink
                  to="/signin"
                  activeStyle={{ color: 'black' }}
                >
                    Sign In
                </NavLink>
                <NavBtn>
                    <NavBtnLink to="/sign-up">Sign Up</NavBtnLink>
                </NavBtn>
            </NavMenu>
           </Nav> 
        </>
    );
};
export default Navbar;
Enter fullscreen mode Exit fullscreen mode

The code snippet above is the navbar component which includes the logo and various links.

Styling the navbar component

In NavbarElements.js, include the following styles.

import { FaBars } from "react-icons/fa";
import { NavLink as Link } from "react-router-dom";
import styled from "styled-components";

export const Nav = styled.nav`
    background: orangered;
    height: 85px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.2rem calc((100vw - 1000px) / 2);
    z-index: 12;
`;
export const NavLogo = styled(Link)`
  cursor: pointer;
  color: #fff;
  font-size: 2rem;
  text-decoration: none;

`;

export const NavLink = styled(Link)`
color: #fff;
display: flex;
align-items: center;
text-decoration: none;
padding: 0 1rem;
height: 100%;
cursor: pointer;
&:hover {
  color: black;
}
`;

export const Bars = styled(FaBars)`
  display: none;
  color: #fff;
  @media screen and (max-width: 768px) {
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(-100%, 75%);
    font-size: 1.8rem;
    cursor: pointer;
  }
`;

export const NavMenu = styled.div`
  display: flex;
  align-items: center;
  margin-right: -24px;

  @media screen and (max-width: 768px) {
    display: none;
  }
`;

export const NavBtn = styled.nav`
  display: flex;
  align-items: center;
  margin-right: 24px;

  @media screen and (max-width: 768px) {
    display: none;
  }
`;

export const NavBtnLink = styled(Link)`
  border-radius: 4px;
  background: transparent;
  padding: 10px 22px;
  color: #fff;
  outline: none;
  border: 1px solid #fff;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  text-decoration: none;
  margin-left: 24px;
  &:hover {
    transition: all 0.2s ease-in-out;
    background: #fff;
    color: #808080;
  }
`;
Enter fullscreen mode Exit fullscreen mode

At the top of the file, we are importing FaBars which is an icon from react-icons. We are also importing styled from styled-components and lastly Navlink as Link from react-router-dom.
Styled components allows you to include pseudo selectors and media queries when writing your styles, similar to how you would write them when using SASS/SCSS.

Go to components\Navbar\index.js and import the following from NavbarElements.js just before the functional component.

import {
    Nav,
    NavLogo,
    NavLink,
    Bars,
    NavMenu,
    NavBtn,
    NavBtnLink,
} from "./NavbarElements";
Enter fullscreen mode Exit fullscreen mode

Implementing routes

In App.js, import the Navbar component and the pages. We will also import BrowserRouter, Routes, Route from react-router-dom.

import './App.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from './pages';
import About from './pages/about';
import Contact from './pages/contact';
import SignUp from './pages/signup';
import SignIn from './pages/signin';

function App() {
  return (
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/signin" element={<SignIn />} />
        <Route path="/sign-up" element={<SignUp />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Adding content to the pages

In the following pages, add placeholder text or any suitable content for your pages.

about.js
const About = () => {
    return (
        <div
            style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100vh'
            }}
        >
            <h1>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Exercitationem, totam.</h1>
        </div>
    );
};

export default About;
Enter fullscreen mode Exit fullscreen mode
contact.js
const Contact = () => {
    return (
        <div
            style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100vh'
            }}
        >
           <h1>Contact Us</h1> 
        </div>
    );
};

export default Contact;

Enter fullscreen mode Exit fullscreen mode
index.js
const Home = () => {
  return (    
    <h1>Welcome to our website!</h1>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode
signin.js

const SignIn = () => {
  return (
    <div>
      <h1>Sign In</h1>
    </div>
  )
}

export default SignIn;

Enter fullscreen mode Exit fullscreen mode
signup.js

const SignUp = () => {
  return (
    <div>
      <h1>Sign Up and get started</h1>
    </div>
  )
}

export default SignUp;

Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we have created a navigation bar using React, styled components and react-router for routing.

Happy coding.

Top comments (22)

Collapse
 
yasarayan profile image
yasar-ayan

Warning: React does not recognize the activeStyle prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase activestyle instead. If you accidentally passed it from a parent component, remove it from the DOM element.

Collapse
 
stephanieopala profile image
Stephanie Opala

This issue is resolved.

Collapse
 
felipebasilio profile image
Felipe Basilio

Where?

Thread Thread
 
stephanieopala profile image
Stephanie Opala

I have updated the index.js code snippet. Feel free to check it out

Collapse
 
beeb12 profile image
Beez B

Hi, where was the issue solved?

Thread Thread
 
stephanieopala profile image
Stephanie Opala

I have updated index.js code snippet. You can have a look at it

Collapse
 
stephanieopala profile image
Stephanie Opala

Thanks for the heads up.

Collapse
 
olajesu070 profile image
OLAJESU BENJAMIN

ERROR in ./src/App.js 21:35-41
export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createPath, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, parsePath, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

ERROR in ./src/components/Navbar/NavbarElements.js 5:0-39
Module not found: Error: Can't resolve 'styled-components' in 'C:\Users\MAX\header\src\components\Navbar'

webpack compiled with 2 errors

Collapse
 
stephanieopala profile image
Stephanie Opala

react-router-dom updated their syntax. Use Routes instead of Switch
You can find more information here.
github.com/howtographql/howtograph...

Collapse
 
olajesu070 profile image
OLAJESU BENJAMIN

Compiled with problems:X

ERROR in ./src/components/Navbar/NavbarElements.js 5:0-39

Module not found: Error: Can't resolve 'styled-components' in 'C:\Users\MAX\nav\src\components\Navbar'

Thread Thread
 
olajesu070 profile image
OLAJESU BENJAMIN

npm install styled-components --save

THIS FIXED IT

many thanks, would like to have some clearity conversation with you

Collapse
 
tagwirei12 profile image
tagwirei12

hello there, I keep getting a blank page on my browser any help?

Collapse
 
davidforer profile image
David Forer

Just wanted to say nice tutorial. Definitely added it to my components.

Collapse
 
stephanieopala profile image
Stephanie Opala

Thank you

Collapse
 
nikhilturale profile image
Nikhil Turale

thanks for this post

Collapse
 
balaji1995ui profile image
Balaji

Hi I follow the above instruction but still not responding in H tags why this happing ..

Collapse
 
balaji1995ui profile image
Balaji

Issue has been fixed.
}/>
component instead of element

Collapse
 
dookiedarnell profile image
💤sleepy sanjay💤

what do yuo mean by this

Thread Thread
 
stephanieopala profile image
Stephanie Opala • Edited

He is referring to to this line of code,
<Route path="/about" element={<About />} /> and the rest of the route
The latest version of react router uses element={<About />} instead of component={<About />}

Collapse
 
yusufgitcollab profile image
Harsh Singh

Thank you so much . It was easy to follow

Collapse
 
grivas97 profile image
grivas97

Hey everything is working for me but for some reason my h1 tags are not showing? this happen to same tutorial i followed on w3school maybe you might have an idea why?

Collapse
 
ayushjii profile image
ayushjii

same here pages are not showing h1 tag or any other