⚛️ React Router

Chapter 10 of 15

What is React Router?

React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

💡 Why React Router? Single-page applications need a way to handle multiple "pages" without refreshing. React Router makes this possible!

Installation

To use React Router, first install the package:

npm install react-router-dom

Basic Routing

Here's a complete example of basic routing:

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

Key Components

BrowserRouter

Wraps your entire application and enables routing:

<BrowserRouter>
  <App />
</BrowserRouter>

Routes and Route

Define your application's routes:

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

Link

Create navigation links without page refresh:

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

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

Layout Component

The Layout component includes navigation and uses Outlet to render child routes:

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

const Layout = () => {
  return (
    <>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>
      </nav>
      
      <Outlet />
    <>
  );
};

export default Layout;

Page Components

Home Page

const Home = () => {
  return <h1>Home Page</h1>;
};

export default Home;

About Page

const About = () => {
  return <h1>About Us</h1>;
};

export default About;

404 Page

const NoPage = () => {
  return <h1>404 - Page Not Found</h1>;
};

export default NoPage;

URL Parameters

You can pass parameters in the URL:

// Define route with parameter
<Route path="/user/:id" element={<User />} />

// Access parameter in component
import { useParams } from "react-router-dom";

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

Programmatic Navigation

Navigate programmatically using the useNavigate hook:

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

function MyComponent() {
  const navigate = useNavigate();
  
  const goToAbout = () => {
    navigate("/about");
  };
  
  return <button onClick={goToAbout}>Go to About</button>;
}

Nested Routes

You can nest routes for complex layouts:

<Route path="/" element={<Layout />}>
  <Route index element={<Home />} />
  
  <Route path="products" element={<Products />}>
    <Route path=":id" element={<ProductDetail />} />
    <Route path="new" element={<NewProduct />} />
  </Route>
</Route>

Active Links

Use NavLink for links that show active state:

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

<NavLink 
  to="/about"
  className={({ isActive }) => isActive ? "active" : ""}
>
  About
</NavLink>
✨ Best Practices:
  • Use BrowserRouter at the root of your app
  • Define routes in a central location
  • Use Link/NavLink instead of <a> tags
  • Implement a 404 page with path="*"
  • Use nested routes for related pages

What's Next?

Now that you understand routing, you're ready to learn about different ways to style your React components!