React Router Guide

react
routing
react-router

Installation

npm install react-router-dom

Basic Setup

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
 
function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/users">Users</Link></li>
          </ul>
        </nav>
 
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/users" element={<Users />} />
        </Routes>
      </div>
    </Router>
  );
}

Route Parameters

<Route path="/users/:id" element={<User />} />
 
// In the User component:
import { useParams } from 'react-router-dom';
 
function User() {
  let { id } = useParams();
  return <h2>User ID: {id}</h2>;
}

Nested Routes

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="users" element={<Users />}>
            <Route path=":id" element={<User />} />
          </Route>
        </Route>
      </Routes>
    </Router>
  );
}
 
function Layout() {
  return (
    <div>
      <nav>{/* navigation items */}</nav>
      <Outlet /> {/* This is where child routes will be rendered */}
    </div>
  );
}

Programmatic Navigation

import { useNavigate } from 'react-router-dom';
 
function HomeButton() {
  let navigate = useNavigate();
  return (
    <button onClick={() => navigate('/')}>
      Go home
    </button>
  );
}

Protected Routes

import { Navigate } from 'react-router-dom';
 
function PrivateRoute({ children }) {
  const auth = useAuth(); // Your authentication hook
  return auth ? children : <Navigate to="/login" />;
}
 
// Usage
<Route
  path="/dashboard"
  element={
    <PrivateRoute>
      <Dashboard />
    </PrivateRoute>
  }
/>

Handling 404 Pages

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="*" element={<NotFound />} />
</Routes>

Using Query Parameters

import { useSearchParams } from 'react-router-dom';
 
function SearchResults() {
  let [searchParams, setSearchParams] = useSearchParams();
  let query = searchParams.get('q');
 
  return (
    <div>
      <h2>Search Results for "{query}"</h2>
      {/* ... */}
    </div>
  );
}

Remember, this cheat sheet covers React Router v6. If you're using an older version, some syntax might be different.