How to add a header, footer components to React router
In this tutorial, we are going to learn about creating and adding a common header, footer components to react-router with the help of an example.
This tutorial assumes that you already have some basic knowledge about react-router otherwise you can check out my React router tutorial.
Creating a header and footer component
First, we need to create two new files called header.js
, footer.js
in our src
folder or components folder.
Now inside header.js
add your react app navigation links like i have shown in the below code.
import React from "react";
import { NavLink } from "react-router-dom";
function Header() {
return (
<nav>
<NavLink exact activeClassName="active" to="/"> Home
</NavLink>
<NavLink activeClassName="active" to="/users"> Users
</NavLink>
<NavLink activeClassName="active" to="/contact"> Contact
</NavLink>
</nav>
);
}
export default Header;
Next, we need to add a footer related code to footer.js
file.
import React from "react";
function Footer() {
return (
<div>
<h1>This is footer</h1>
</div>
);
}
export default Footer;
Adding header and footer
We successfully created two components, now we will add a header
, footer
components to index.js
file, so that we can see the both components on every page we navigate.
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { Route, BrowserRouter as Router, Switch } from "react-router-dom";
import App from "./App";
import Users from "./users";
import Contact from "./contact";
import Notfound from "./notfound";
import Header from "./header";import Footer from "./footer";
const routing = (
<Router>
<div>
<Header /> <hr />
<Switch>
<Route exact path="/" component={App} />
<Route path="/users" component={Users} />
<Route path="/contact" component={Contact} />
<Route component={Notfound} />
</Switch>
<Footer /> </div>
</Router>
);
ReactDOM.render(routing, document.getElementById("root"));