Building Navbar with React || Open Page without Reloading
Today, we are going to build a navbar with React where we will try to open the page without reloading.
How to build a navbar with React that doesn't reload the page?
import React from "react";
import { NavLink } from "react-router-dom";
const Navbar = () => {
return (
<>
<header>
<div className="container">
<div className="logo-brand">
<a to="/">Manoj</a>
</div>
</div>
<nav>
<ul>
<li>
<NavLink to="/">Home</NavLink>
</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
<li>
<NavLink to="/service">Services</NavLink>
</li>
<li>
<NavLink to="/contact">Contact</NavLink>
</li>
<li>
<NavLink to="/register">Register</NavLink>
</li>
<li>
<NavLink to="/login">Log In</NavLink>
</li>
</ul>
</nav>
</header>
</>
);
};
export default Navbar;
In order to make components, make src/components and create a file named as Navbar.jsx inside it.
The above code helps to create navbar components.
In order to create a link which doesn't reload the page, you need to use <NavLink to="/path">name</NavLink>.
Recommended by LinkedIn
You can call the navbar on each of the pages individually which takes a lot of time. So for such a reusable component, you can directly call it inside App.jsx.
import Navbar from './components/Navbar';
<BrowserRouter>
// Navbar is shown before other paths are handled. So it can be seen in every pages.
<Navbar />
<Routes>
<Route exact path="/" element={<Home />} />
<Route path='/about' element={<About />}/>
<Route path='/contact' element={<Contact />}/>
<Route path='/service' element={<Service />}/>
<Route path='/register' element={<Register />}/>
<Route path='/login' element={<Login />}/>
<Route path='/*' element={<NotFound />} />
</Routes>
</BrowserRouter>
Conclusion
Congrats, you have successfully created a navbar with React that opens pages without reloading.
Remember if you use <a> tag instead of <NavLink> then the page gets reloaded.