AI Hints
Home›React Tutorial›Routing
React · Lesson 67 of 120

Routing

Pages in one app.

⏱ 2 min read▶ Video at 55:38🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Real apps have many pages. A home page, a shop, an about page. In a single page app, React swaps components when the address changes. React Router is the most popular library for this.

  • Many pages
  • Swap components
  • React Router

Three pages

React Router maps addresses to components. Each route pairs a path with an element to show. Link changes the address without reloading the page. Memory router keeps the address in memory, for this demo. In a real app, you'd use browser router, which uses the address bar. We click shop. Run it.

App.jsxjsx
import { MemoryRouter, Routes, Route, Link } from "react-router";
function Home() { return <h2>Welcome to Northwind Bikes</h2>; }
function Shop() { return <h2>All bikes</h2>; }
function About() { return <h2>Open daily, 9 to 6</h2>; }
export default function App() {
  return (
    <MemoryRouter>
      <nav><Link to="/">Home</Link> | <Link id="shop" to="/shop">Shop</Link> | <Link to="/about">About</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/shop" element={<Shop />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </MemoryRouter>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#shop"}]

Use Link instead of a normal anchor tag. A normal link reloads the whole page, and throws away your state. Link just changes the address, and React swaps the page.

keyvalue
<Link to>no reload
<a href>full reload
Statekept
Installnpm i react-router

Summary

Routes map paths to components, and Link moves between them. Next, links and params.

Key takeaways
  • <Routes>
  • <Route path>
  • <Link to>
Next up: Links and Params — product pages