Home / React / Lesson 9

React Router — multiple screens

Intermediate 8 min read Lesson 9 of 11

Vite + React is a single HTML file. Clicking <a href="/about"> would ask the server for /about, which may 404. React Router intercepts navigation and renders a different component without a full reload.

Install: npm install react-router-dom. The v6 API (still the one you will meet in docs and jobs):

import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';

function Lesson() {
  const { slug } = useParams();
  return <h1>Lesson: {slug}</h1>;
}

export default function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/lessons/jsx">JSX</Link>
      </nav>
      <Routes>
        <Route path="/" element={<p>Home</p>} />
        <Route path="/lessons/:slug" element={<Lesson />} />
      </Routes>
    </BrowserRouter>
  );
}

Use <Link>, not raw <a>, for in-app routes. For production on GitHub Pages you often need a hash router or host rewrite rules so refresh on /lessons/jsx does not 404 — that is a hosting concern, not a React bug.