Building the Components
In this article, we are building 5 components.
- Navigation.jsx and Footer.jsx those are common for all routes.
- Home.jsx, About.jsx and Contact.jsx those are the routes.
First, create components directory inside src. All our components will be coded inside it.
1. Navigation.jsx
This is the topmost section of our app which deals with the navigation of our routes.
We are using <Link> instead of <a> tag. Clicking each Link will route to the specific path described.
- <Link to=”/”>Home</Link> – The route to the home page that is http://localhost:3000
- <Link to=”/about”>About</Link> – About page route that is, http://localhost:3000/about
- <Link to=”/contact”>Contact</Link> – Route to contact page that is http://localhost:3000/contact
import React from “react”; |
|
import { Link, withRouter } from “react-router-dom”; |
|
function Navigation(props) { |
|
return ( |
|
<div className=”navigation”> |
|
<nav class=”navbar navbar-expand navbar-dark bg-dark”> |
|
<div class=”container”> |
|
<Link class=”navbar-brand” to=”/”> |
|
React Multi-Page Website |
|
</Link> |
|
<div> |
|
<ul class=”navbar-nav ml-auto”> |
|
<li |
|
class={`nav-item ${ |
|
props.location.pathname === “/” ? “active” : “” |
|
}`} |
|
> |
|
<Link class=”nav-link” to=”/”> |
|
Home |
|
<span class=”sr-only”>(current)</span> |
|
</Link> |
|
</li> |
|
<li |
|
class={`nav-item ${ |
|
props.location.pathname === “/about” ? “active” : “” |
|
}`} |
|
> |
|
<Link class=”nav-link” to=”/about”> |
|
About |
|
</Link> |
|
</li> |
|
<li |
|
class={`nav-item ${ |
|
props.location.pathname === “/contact” ? “active” : “” |
|
}`} |
|
> |
|
<Link class=”nav-link” to=”/contact”> |
|
Contact |
|
</Link> |
|
</li> |
|
</ul> |
|
</div> |
|
</div> |
|
</nav> |
|
</div> |
|
); |
|
} |
|
export default withRouter(Navigation); |
view rawNavigation.jsx hosted with by GitHub
I also added a simple logic in this component to trigger different color active navigation item. In Bootstrap adding a class active will show an active color for that link. In React, props.location.pathname will give the exact path of the current route.
I have combined those two and if the pathname if the current pathname is the same as the route, a class named active is added to the link.
Note:- To get the exact pathname, the component must be wrapped inside withRouter. You can see that I exported the Navigation component wrapped inside withRouter(line 61).