DEV Community

nedajahanfar
nedajahanfar

Posted on

Introduction to React: Understanding the Basics-part.7

Navigation in React vs. Traditional Webpages

In traditional websites, when you click a link , the browser sends a request to the server, and the server responds with a completely new HTML page. This means:

  1. The entire page reloads.
  2. The server has to send back all the content, even if only a small part of the page changes.

But in React, the browser doesn't reload the entire page. Instead, React only updates the necessary components inside the root

, making navigation much faster.

_Traditional websites → Like an elevator. Clicking a link takes you to a completely different floor (new page request).

React navigation → Like a slideshow. Clicking a link just changes slides, keeping the structure the same while swapping out the necessary content._

How Does React Achieve This?

React doesn’t handle navigation on its own—it uses a separate library called React Router. This library creates an illusion of navigation by:
Changing the URL without refreshing the page.
Updating the displayed components based on the URL.

_In React, we don’t use

<a href="/"> 

for navigation because:

They automatically reload the page, breaking React’s smooth updates.

Instead, we use from react-router-dom, which updates the URL and changes components without a full reload._

Getting Started with React Navigation (React Router)

Install React Router:

npm install react-router-dom

Set Up a Basic Router:
In your App.js, import BrowserRouter, Routes, and Route.

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";

Create a Navbar that is always visible and contains Link elements.
Below the Navbar, use to define which component should be displayed for each link.
Each has a to="..." that must match a

<Route path="...">

When a user clicks a Link, React Router checks all Route elements inside and renders the one with a matching path.

import { Link } from "react-router-dom";

function Navbar() {
  return (
    <nav>
      <Link {% embed to %}="/">Home</Link>
      <Link {% embed to %}="/about">About</Link>
      <Link {% embed to %}="/contact">Contact</Link>
    </nav>
  );
}

export default Navbar;

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Navbar from "./Navbar";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";

function App() {
  return (
    <BrowserRouter>
      <Navbar />  
      <Routes>
        <Route {% embed path %}="/" element={<Home />} />
        <Route {% embed path %}="/about" element={<About />} />
        <Route {% embed path %}="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Top comments (0)