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
- Setting up the React environment
- Installing the required dependencies
- Structuring the project
- Creating the navbar component
- Styling the navbar component
- Implementing routes
- Adding content to the pages
- Conclusion
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
Once the process is done, run the following command to get into the my-app folder.
cd my-app
Installing the required dependencies
Install react-router-dom
using the following command in your terminal.
npm install react-router-dom
We will use styled components for styling, therefore install it using the command below.
npm install --save styled components
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
Once the installation of the above is done, start the React application using the following command.
npm start
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;
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;
}
`;
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";
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;
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;
contact.js
const Contact = () => {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh'
}}
>
<h1>Contact Us</h1>
</div>
);
};
export default Contact;
index.js
const Home = () => {
return (
<h1>Welcome to our website!</h1>
);
};
export default Home;
signin.js
const SignIn = () => {
return (
<div>
<h1>Sign In</h1>
</div>
)
}
export default SignIn;
signup.js
const SignUp = () => {
return (
<div>
<h1>Sign Up and get started</h1>
</div>
)
}
export default SignUp;
Conclusion
In this article, we have created a navigation bar using React, styled components and react-router for routing.
Happy coding.
Top comments (23)
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 lowercaseactivestyle
instead. If you accidentally passed it from a parent component, remove it from the DOM element.This issue is resolved.
Where?
I have updated the index.js code snippet. Feel free to check it out
Hi, where was the issue solved?
I have updated index.js code snippet. You can have a look at it
Thanks for the heads up.
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
react-router-dom
updated their syntax. Use Routes instead of SwitchYou can find more information here.
github.com/howtographql/howtograph...
hello there, I keep getting a blank page on my browser any help?
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'
npm install styled-components --save
THIS FIXED IT
many thanks, would like to have some clearity conversation with you
Just wanted to say nice tutorial. Definitely added it to my components.
Thank you
thanks for this post
Thank you so much . It was easy to follow
Hi I follow the above instruction but still not responding in H tags why this happing ..
Issue has been fixed.
}/>
component instead of element
what do yuo mean by this
He is referring to to this line of code,
<Route path="/about" element={<About />} />
and the rest of theroute
The latest version of react router uses
element={<About />}
instead ofcomponent={<About />}
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?
same here pages are not showing h1 tag or any other
Thanks. It would have been super nice if you would have added output screen as well since some people need expected outcome before code :)