Client-side routing
🏠The everyday picture
A big book with tabbed dividers. Flicking to the "Contacts" tab is instant because the whole book is already in your hands; you don't go back to the library for each section.
📘What it really is
- A React app is one HTML page (Module 31). Client-side routing shows different screens for different addresses without asking the server for a new page each time:
/shows the dashboard;/enquiries/newshows the form;-
/enquiries/E104shows one enquiry. -
The address bar, Back button and bookmarks all still work, which people expect. A single page with no addresses frustrates them: they can't share a link or go back.
-
React Router is the most widely used routing library:
npm install react-router
import { BrowserRouter, Routes, Route } from "react-router";
<BrowserRouter>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/enquiries/new" element={<NewEnquiry />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
path="*"catches any address that matches nothing: your 404 page.- Hosting note: the server must send
index.htmlfor every address, or reloading/enquiries/newgives a 404. Hosts like Netlify and Vercel have a setting for this; on Apache hosting it's a rule in.htaccess.
🖱️Try it
Install React Router. Set up routes for the dashboard (/), the new-enquiry form (/enquiries/new) and a
NotFound page. Visit each address by typing it in the address bar, and try an address that doesn't exist.
✅Quick check
Why should each screen in an app have its own address?
Show the answer
So Back, bookmarks, sharing links and reloading all work as people expect.
A deployed React app works until you reload on /enquiries/new, which shows the host's 404. Why?
Show the answer
The server looks for a real file at that path. It must be set to send index.html for all app addresses.
