React Router DOM
The industry standard library for client-side routing in React, using declarative components to match URLs to UI.
Declarative Routing
While you could build your own client-side router by listening to the popstate event, it gets incredibly complex when dealing with nested layouts, URL parameters, and query strings.
react-router-dom is the de facto standard library for routing in React. It allows you to declare your application's routes using standard JSX components.
The core idea is simple: You define a list of <Route> components. When the URL changes, the router looks through the list, finds the one that matches the URL, and renders its component.
Dynamic Parameters and Catch-Alls
URLs are rarely static. You often need URLs like /users/123 or /products/shoes.
React Router allows you to define dynamic segments using a colon, like <Route path="/users/:id" />.
When a user navigates to /users/123, React Router extracts 123 and makes it available to the rendered component via the useParams() hook.
You can also define a "catch-all" route using path="*" to render a 404 Not Found page if no other routes match.
The Core Components
A standard React Router setup involves three main layers:
1. <BrowserRouter>: Wraps your entire app. It connects your app to the browser's URL history.
2. <Routes>: Acts as a switch. It looks at all its child <Route> components and picks the *best* match for the current URL.
3. <Route>: Defines a mapping between a URL path and a React component (e.g., <Route path="/about" element={<About />} />).
To navigate between pages, you use the <Link to="/path"> component instead of standard <a> tags. <Link> intercepts the click and prevents the browser from reloading the page.
The Router Engine
Click the links in the mock browser to see how React Router's <Routes> component matches the URL to a specific <Route> declaration, extracting dynamic parameters along the way.
Home Page
Welcome to the app.
Click the links in the mock browser to see the Router engine match URLs to components.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
<BrowserRouter>connects your app to the browser's URL.<Routes>evaluates child routes and picks the best match.<Route>maps a specificpathto a componentelement.- Dynamic segments (like
:id) are accessed viauseParams(). - Always use
<Link>instead of<a>for internal navigation.
Done with this concept?
Mark it complete to track your progress. No login needed.