Building Navbar with React || Open Page without Reloading

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?

  • First, let us create a navbar component:

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>.


  • After that, all the work is done on the App.jsx.

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';        

  • After this, you can call this component inside BrowserRouter before handling the Routes.

<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.

To view or add a comment, sign in

More articles by Manoj Shrestha

Insights from the community

Others also viewed

Explore topics