React Routing – Navigating Pages with React Router v6

16/06/2025

React Routing – Navigating Pages with React Router v6

Single Page Applications (SPAs) need routing to move between different pages/views. React Router is the most popular library for handling routes in React.

🚦 1. What is React Router?

  • React Router lets you add multiple pages or views in your React app.

  • It handles:

    • URL changes

    • Page navigation

    • Dynamic routing (e.g., user profiles, product pages)


📦 2. Installation


npm install react-router-dom


💡 This installs react-router-dom, which is the official router for web apps in React.


🧱 3. Basic Setup with React Router v6


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

import Home from './pages/Home';

import About from './pages/About';


function App() {

  return (

    <BrowserRouter>

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

      </Routes>

    </BrowserRouter>

  );

}


🔍 Explanation:

  • BrowserRouter: Enables routing using the browser’s URL.

  • Routes: Container for all Route definitions.

  • Route: Defines path and which component to show.


🔁 4. Navigation with Link

Instead of using <a href="">, use React Router’s Link:


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


function Navbar() {

  return (

    <nav>

      <Link to="/">Home</Link> |

      <Link to="/about">About</Link>

    </nav>

  );

}


💡 This prevents full page reloads and enables smooth SPA navigation.


🔍 5. Dynamic Routing


<Route path="/product/:id" element={<ProductPage />} />


Inside ProductPage.js:


import { useParams } from 'react-router-dom';


function ProductPage() {

  const { id } = useParams();

  return <h2>Product ID: {id}</h2>;

}


🧠 Explanation:

  • :id is a URL parameter.

  • useParams() lets you access it inside the component.


🚫 6. Catch-All / 404 Route


<Route path="*" element={<NotFound />} />


This shows the NotFound component for any route that doesn’t match.