React Router

React Router is the standard routing library for React. It allows you to build single-page applications with navigation without having to refresh the page.

Basic Setup

To use React Router, you need to install react-router-dom. The main components you'll use are `BrowserRouter`, `Routes`, and `Route`.

JavaScript

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>
  );
}

Linking Between Pages

In standard HTML, we use <a> tags. In React Router, we use the Link component to prevent the page from refreshing.

JavaScript

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

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

URL Parameters

You can capture dynamic parts of the URL (like a user ID) using the : syntax and the useParams hook.

JavaScript

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

// In User.js
const { id } = useParams();

Note: Always wrap your entire application in BrowserRouter at the highest level (usually in index.js or App.js).