Sub topic 3
Defining routes and how paths match
This chapter assumes you can write React function components and JSX, you know basic JavaScript (ES modules, arrays of objects), and you have a router running with createBrowserRouter and RouterProvider. It covers what a route object is, how React Router turns a URL into a list of matching routes, and which mistakes cause most "why does this route not render" problems.
Routes are plain objects
With the data router API, your whole route table is an array of objects passed to createBrowserRouter. Each object is a route. The properties you will use most:
| Property | Purpose |
|---|---|
| `path` | The URL pattern this route matches, relative to its parent. |
| `element` | The React element rendered when the route matches. |
| `children` | An array of nested routes. |
| `index` | If `true`, the route matches the parent's exact path. It has no `path`. |
| `loader`, `action` | Data functions, covered in later chapters. |
| `errorElement` | What to render when this route or a descendant fails. |
| `caseSensitive` | Makes this route's path case sensitive. The default is insensitive. |
Because routes are data, you can inspect, generate, and test them without rendering anything. This chapter uses that property to show how matching works.
Static, dynamic, and splat segments
A path is split into segments at each /. Each segment is one of three kinds.
| Pattern | Kind | Matches | Value captured |
|---|---|---|---|
| `users` | Static | Only the text `users` | None |
| `:userId` | Dynamic | Any single non-empty segment | `params.userId` |
| `files/*` | Splat | Everything after `files/`, including more slashes | `params["*"]` |
| `:lang?` | Optional | The segment, or nothing | `params.lang` or `undefined` |
A dynamic segment never matches across a slash. /users/:userId matches /users/42 but not /users/42/edit. A splat does cross slashes, so files/* matches /files/a/b.txt with params["*"] equal to a/b.txt.
Matching is case insensitive unless you set caseSensitive: true, and a trailing slash is ignored. /Users/42/ matches users/:userId. Captured values keep the case they had in the URL.
Relative paths and nesting
A child route's path is joined to its parent's path. A parent with path: "users" and a child with path: ":userId" produces the full pattern /users/:userId. Do not repeat the parent's path in the child.
A route with no path is a layout route. It matches without consuming any URL segments and exists only to wrap its children in shared UI. An index route is the child that renders when the URL ends exactly at the parent.
Here is a route table that uses all of these:
import { createBrowserRouter, RouterProvider } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <h1>Shell</h1>,
children: [
{ index: true, element: <p>Home</p> },
{
path: "users",
children: [
{ index: true, element: <p>All users</p> },
{ path: "new", element: <p>New user form</p> },
{ path: ":userId", element: <p>One user</p> },
],
},
{ path: "files/*", element: <p>File browser</p> },
{ path: "*", element: <p>Not found</p> },
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}The users route has no element. It only groups its children under /users, and its children render directly in the parent's Outlet. The next chapters cover how Outlet places child output.
How a URL becomes a match
React Router does not try routes top to bottom and stop at the first hit. It flattens the tree into every possible full path, scores each one, and picks the best match.
The scoring rules, in order of importance:
- A static segment scores higher than a dynamic segment.
- A dynamic segment scores higher than a splat.
- An index route scores higher than a plain route with the same path.
- If scores tie, the route defined earlier wins.
The result is that the order of sibling routes rarely matters. In the table above, /users/new matches both new and :userId, but the static new wins even though it is not listed last.
The match is a chain, not a single route. For /users/new the matches are the root route, the users route, and the new route. Each one renders inside its parent, which is why a layout can persist while only the inner part changes.
Inspecting matches with matchRoutes
The matchRoutes function runs the same algorithm without rendering. It is useful for learning and for debugging a table that behaves unexpectedly.
import { matchRoutes } from "react-router-dom";
const routes = [
{
path: "/",
children: [
{ index: true },
{
path: "users",
children: [{ index: true }, { path: "new" }, { path: ":userId" }],
},
{ path: "files/*" },
{ path: "*" },
],
},
];
function show(url) {
const matches = matchRoutes(routes, url);
if (!matches) {
console.log(url, "-> no match");
return;
}
const chain = matches.map((m) => m.route.path ?? "(index)");
console.log(url, "->", chain.join(" > "), matches.at(-1).params);
}
show("/"); // / > (index) {}
show("/users"); // / > users > (index) {}
show("/users/new"); // / > users > new {}
show("/users/42"); // / > users > :userId { userId: "42" }
show("/files/a/b.txt"); // / > files/* { "*": "a/b.txt" }
show("/nothing"); // / > * { "*": "nothing" }Each comment shows the logged result. Note that /users/new resolves to new, not :userId.
Common errors
- Leading slash on a child path. A child path that starts with
/is absolute, so it must begin with the full parent path.{ path: "/users", children: [{ path: "/new" }] }throws an error about an absolute child path. Write"new"instead. - Expecting a dynamic segment to match a nested URL.
/users/:userIdwill not match/users/42/posts. Add a child route, or use a splat if you really want everything. - Putting
*in the middle of a path. A splat is only valid as the last segment."files/*/edit"does not do what it appears to. - Giving an index route a path. An index route has no
pathand nochildren. Its position in the parent defines where it matches. - Relying on order. Moving a route up or down in a sibling list usually changes nothing. If behavior changes, you probably have two routes with equal scores.
- No catch-all. When no route matches, React Router renders its built-in 404 error screen. Add a
*route, or anerrorElementon the root, to control that page.
Exercise
Given routes with the paths /products/:id, /products/new, and /products/* as siblings (listed in that order), which route matches /products/new, which matches /products/7, and which matches /products/7/reviews?
Show answer
/products/new matches the static new route, because static segments outrank dynamic ones. /products/7 matches :id with params.id equal to "7". /products/7/reviews matches only the splat, with params["*"] equal to "7/reviews", because :id cannot match across a slash.
Exercise
A child route is written as { path: "/settings" } inside a parent with path: "account". Why does this fail, and how do you fix it?
Show answer
A path starting with / is absolute, and an absolute child path must start with its parent's full path (/account). Change the child to { path: "settings" } so it is joined to the parent and matches /account/settings.