React Router DOM

Client-side routing for React applications

🧭 What is React Router DOM?

React Router DOM enables navigation between different pages in React applications without page reloads. It provides components and hooks for creating dynamic, client-side routing with URL parameters and nested routes.


// Simple routing example
import { BrowserRouter, Routes, Route } from 'react-router-dom';

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

Key Router Concepts

🌐

BrowserRouter

Main router component for web apps

<BrowserRouter>
  <App />
</BrowserRouter>
🛣️

Routes & Route

Define paths and components to render

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

Link

Navigate without page reload

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

Hooks

Access routing information

const navigate = useNavigate();
const params = useParams();

🔹 Setting Up React Router

Install React Router DOM and wrap your application with BrowserRouter to enable routing functionality throughout all components in your React app.

# Install React Router
npm install react-router-dom
// index.js or main.jsx
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom/client';
import App from './App';

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

🔹 Basic Routes

Define routes using Routes and Route components. Each route maps a URL path to a React component that should be displayed when users visit that path.

// App.js
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';

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

🔹 Navigation with Link

Use Link component instead of anchor tags to navigate between pages without full page reloads. This keeps your React app fast and maintains state.

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

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

// NavLink for active styling
import { NavLink } from 'react-router-dom';

<NavLink 
  to="/about" 
  className={({ isActive }) => isActive ? 'active' : ''}
>
  About
</NavLink>

🔹 URL Parameters

Capture dynamic values from URLs using parameters. Perfect for displaying specific items like user profiles, blog posts, or product details based on the URL.

// Define route with parameter
<Route path="/user/:userId" element={<UserProfile />} />
<Route path="/post/:postId" element={<Post />} />

// Access parameters in component
import { useParams } from 'react-router-dom';

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

// Link with parameter
<Link to="/user/123">View User</Link>

🔹 Programmatic Navigation

Navigate programmatically using the useNavigate hook. Useful for redirecting after form submissions, authentication, or any action that requires changing the current page.

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

function LoginForm() {
  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefault();
    // After successful login
    navigate('/dashboard');
    
    // Navigate back
    // navigate(-1);
    
    // Replace current entry
    // navigate('/home', { replace: true });
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Login</button>
    </form>
  );
}

🔹 Nested Routes

Create nested route structures for complex layouts. Child routes render inside parent components using the Outlet component, perfect for dashboards and multi-level navigation.

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

// Parent component with Outlet
function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <nav>
        <Link to="profile">Profile</Link>
        <Link to="settings">Settings</Link>
      </nav>
      <Outlet /> {/* Child routes render here */}
    </div>
  );
}

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

🔹 404 Not Found Page

Handle unknown routes with a catch-all route using the asterisk path. This displays a custom 404 page when users navigate to non-existent URLs.

function NotFound() {
  return (
    <div>
      <h1>404 - Page Not Found</h1>
      <Link to="/">Go Home</Link>
    </div>
  );
}

// Add at the end of routes
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="*" element={<NotFound />} />
</Routes>

🔹 Protected Routes

Create protected routes that require authentication. Redirect unauthorized users to login page while allowing authenticated users to access protected content seamlessly.

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

function ProtectedRoute({ children }) {
  const isAuthenticated = checkAuth(); // Your auth logic

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return children;
}

// Usage
<Routes>
  <Route path="/login" element={<Login />} />
  <Route 
    path="/dashboard" 
    element={
      <ProtectedRoute>
        <Dashboard />
      </ProtectedRoute>
    } 
  />
</Routes>

🔹 Complete Example

A full routing example with navigation, nested routes, and parameters. This demonstrates how all routing concepts work together in a real application.

// App.js
import { Routes, Route, Link, Outlet } from 'react-router-dom';

function Layout() {
  return (
    <div>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/products">Products</Link>
        <Link to="/about">About</Link>
      </nav>
      <Outlet />
    </div>
  );
}

function Products() {
  return (
    <div>
      <h2>Products</h2>
      <Link to="/products/1">Product 1</Link>
      <Link to="/products/2">Product 2</Link>
    </div>
  );
}

function ProductDetail() {
  const { id } = useParams();
  return <h2>Product {id}</h2>;
}

function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<Home />} />
        <Route path="products" element={<Products />} />
        <Route path="products/:id" element={<ProductDetail />} />
        <Route path="about" element={<About />} />
      </Route>
    </Routes>
  );
}

🧠 Test Your Knowledge

Which component is used for navigation without page reload?