Start learning free

LESSON 96 OF 161 · FRONTEND: REACT ROUTES AND SHARED STATE

React Router

Practice

In the last lesson you built a router by hand: stop the link, write the address, keep the path in state, listen to Back. React Router, the package react-router-dom, does all of that for you. BrowserRouter, already in src/main.jsx, wraps your App, keeps the address in its own state and hears the Back button.

Inside it, Routes looks at the address and draws the one Route whose path matches. A Route's element holds the JSX to draw. A Link is drawn as an ordinary a, but its click changes the address without loading a page, just like your go. For a help page, it would look like this:

<Link to="/help">Help</Link>

<Routes>
  <Route path="/help" element={<HelpPage />} />
</Routes>

Because the page is chosen from the address, Back works, and a reload on /cart stays on the cart. The check adds a Mug to the cart, clicks Cart, presses Back, clicks Cart again and reloads. Your page must give:

> click "Cart"
  request: GET /api/cart -> 200
  screen: section "Cart": item: Mug × 1 $12, text: Total: $12
> the address bar
  /cart
> press the browser's Back button
  request: GET /api/products -> 200
  screen: section "Products" with the 8 products
> the address bar
  /
> reload the page   (on /cart, after a second click on Cart)
  request: GET /api/cart -> 200
  screen: section "Cart": item: Mug × 1 $12

Your task: in src/App.jsx, add Routes inside main, with a Route for "/" that draws ProductsPage and one for "/cart" that draws CartPage. Then put two Links in the nav: Products to "/" and Cart to "/cart". The import line is already there.


Assignment
Follow the Coding Tutorial to give the shop two routes and a nav made of Links.


Hint
A Link takes to where an a takes href. A Route closes itself, and its element is JSX in braces: element={<CartPage />}.


STEP 1 OF 5
    Ctrl + Enter to check