intro-to-programming

🧭 React Router DOM

react-router-dom is the standard routing library for React web applications.
It lets you build single-page apps (SPAs) with multiple pages, routes, and navigation β€” all without reloading the browser.


πŸš€ Installation

First, install react-router-dom via npm or yarn:

npm install react-router-dom
# or
yarn add react-router-dom

Make sure you’re using React v18+ and react-router-dom v6+.


πŸ“¦ Basic Project Structure

src/
β”œβ”€β”€ App.jsx
β”œβ”€β”€ main.jsx
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ Home.jsx
β”‚   β”œβ”€β”€ About.jsx
β”‚   └── NotFound.jsx
└── components/
    └── Navbar.jsx

πŸ”§ Initial Setup

Wrap your app with the BrowserRouter in main.jsx:

// main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

πŸ›€οΈ Define Routes

Use Routes and Route in App.jsx:

// App.jsx
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';
import Navbar from './components/Navbar';

function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </>
  );
}

export default App;

🧭 Navigation

Use Link or NavLink instead of <a> tags to avoid full page reloads:

// components/Navbar.jsx
import { Link, NavLink } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <NavLink to="/">Home</NavLink> | <NavLink to="/about">About</NavLink>
    </nav>
  );
}

πŸ”Έ NavLink adds an active class when the route is matched


πŸ“„ Route Components

// pages/Home.jsx
function Home() {
  return <h1>🏠 Welcome to the Home Page</h1>;
}

export default Home;

// pages/About.jsx
function About() {
  return <h1>ℹ️ About This App</h1>;
}

export default About;

// pages/NotFound.jsx
function NotFound() {
  return <h1>404 - Page Not Found</h1>;
}

export default NotFound;

πŸ”„ Route Parameters

Dynamic routes using :param syntax:

<Route path="/user/:id" element={<UserProfile />} />

Access the parameter using useParams():

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

function UserProfile() {
  const { id } = useParams();
  return <h2>User ID: {id}</h2>;
}

πŸ” Redirects

Use Navigate for programmatic redirects:

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

function ProtectedRoute({ isLoggedIn }) {
  return isLoggedIn ? <Dashboard /> : <Navigate to="/login" />;
}

πŸ§ͺ Nested Routes (Optional)

<Route path="/dashboard" element={<Dashboard />}>
  <Route path="profile" element={<Profile />} />
  <Route path="settings" element={<Settings />} />
</Route>

Use <Outlet /> in the parent component (Dashboard) to render child routes.


πŸ“š Learn More


βœ… Best Practices

Do This Avoid This
Use Link/NavLink for navigation Using <a> tags
Use useParams, useNavigate Manually parsing window.location
Structure pages/components cleanly Putting all routes in one file
Handle * path for 404 pages Letting bad URLs crash the app

🏁 Summary

Feature Usage
BrowserRouter Wraps the app for routing
Routes + Route Defines each route/page
Link / NavLink Navigation without reloading
useParams() Access dynamic route segments
Navigate Redirect to another route
Outlet Render nested routes

React Router DOM gives your app navigation, structure, and page control β€” all within a modern, SPA-friendly API.