A plain link, <a href="/cart">, makes the browser leave the page. It asks the server for a whole new page and starts your React app again from nothing. A shop with several pages can do better: stay on the same page and only change what React draws.
Three browser tools make that possible. event.preventDefault() in a click handler stops the browser from following the link. window.history.pushState(null, "", "/help") writes a new address in the address bar, and a new entry in the history, without loading anything. When the visitor presses Back, the window fires a popstate event, and the old address is already in window.location.pathname. A link to a help page could stay on the page like this:
function openHelp(event) {
event.preventDefault();
window.history.pushState(null, "", "/help");
}
The new address alone doesn't change the screen: React draws again only when state changes. So App keeps the path in state and picks the page from it. Every click sets the path, and so does every popstate. This is what a router does.
The check adds a Mug to the cart, clicks Cart, presses Back and then opens /cart directly. 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 / > open /cart request: GET /api/cart -> 200 screen: section "Cart": item: Mug × 1 $12
Your task: in src/App.jsx, keep the path in a state variable and draw CartPage when it is "/cart". In go, stop the link, put its href in the address bar and in the state. In an effect, listen to popstate, and remove the listener in the effect's cleanup.
Assignment
Follow the Coding Tutorial to turn the shop's two plain links into links that change the page without loading a new one, and make the browser's Back button work.
Hint
After pushState, the address is right but the screen is not: call setPath too. Back doesn't click anything: it fires popstate on window.
Free plan: 30 tutor messages. PRO is unlimited.
