Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 50 ยท Practice and Review

Exercises: Declarative Routing

Eight graded React Router exercises on route matching, links, params and nested layouts. Four are runnable test-driven functions, four are real-code design tasks, all with solutions.

Reading about a router is not the same as thinking in routes. These eight exercises make you do the thinking: decide which route wins, write the route tree for a sitemap, resolve a relative link by hand, and trace which components a URL mounts. They cover the first four chapters of this tutorial, from Routes and Matching to Dynamic Segments and Nested Routes and Outlet.

The exercises come in two kinds, because React Router itself cannot run in the live editor:

  • Logic exercises (2, 3, 5 and 7) are runnable. You get a function stub and a table of tests. Edit the function until every row says pass. These are small versions of what the real router does internally, so solving them also explains why it behaves as it does.
  • Design exercises (1, 4, 6 and 8) are about the real React Router API. You write the JSX or configuration on paper (or in your own project) and compare it with the solution. Their code blocks are read-only, because the editor cannot install the package.

Try each exercise for at least five minutes before you open the hint, and read the hint before the solution. All code targets React Router 7 in declarative mode (import { ... } from 'react-router').

Do the logic exercises in order. Exercise 3 reuses the function from exercise 2, and exercise 7 builds on the idea of exercise 2 with a tree.

Matching

1. A route tree for a sitemap (design)

A small site has these pages. Write the <Routes> that serves them.

  • / home
  • /about
  • /blog the list of posts
  • /blog/:slug one post (for example /blog/hello-world)
  • /blog/new a form to write a post
  • anything else: a "page not found" screen

Then answer: both /blog/:slug and /blog/new match the URL /blog/new. Which one renders, and does the order of the lines in your JSX matter?

Show hint

Think about how React Router chooses: it does not read your routes top to bottom. It gives every route a score based on how specific its path is, and picks the highest score. Is a fixed word more specific than a placeholder? Also remember that path="*" is the catch-all (see 404 Pages and Catch-All Routes).

Show solution
JSX
// App.jsx - React Router (read-only)
import { Routes, Route } from 'react-router';

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="blog" element={<PostList />} />
      <Route path="blog/new" element={<NewPost />} />
      <Route path="blog/:slug" element={<Post />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

/blog/new renders NewPost. A static segment (new) scores higher than a dynamic one (:slug), so the order of the two lines does not matter: you may write blog/:slug first and the result is the same. The same ranking is why * can sit anywhere and still only catches what nothing else matched. Putting the catch-all last is a readability habit, not a requirement. Exercise 3 implements a simplified version of this scoring.

2. Write matchPath (logic)

Write matchPath(pattern, path). It returns an object with the params if the path matches the pattern, or null if it does not. Patterns can contain static segments (blog), params (:slug) and a final splat (*). A splat captures the rest of the path under the key "*", without a leading slash. Params must be URL-decoded. The real router exports a function with the same name; this one is a simplified version.

Exercise 2: matchPath (starter)
Show hint

Turn each string into an array with split('/').filter(Boolean). Loop over the pattern pieces. A piece starting with : stores decodeURIComponent(pathPiece) under its name. A piece equal to * stores everything from this position on, joined with /, and returns at once. Any other piece must equal the path piece exactly, otherwise return null. After the loop the two arrays must have the same length, or the path had extra pieces.

Show solution
Solution 2: matchPath

Two details are worth remembering. A splat is allowed to match an empty remainder, so /files matches files/*. And decoding belongs here, not later: the router hands your component a decoded string, which is also why you must still validate it (see Dynamic Segments and useParams).

3. Pick the best route (logic)

Several patterns can match one URL, and the router has to choose. Write pickRoute(patterns, path), which returns the most specific matching pattern (or null). Use this score for a pattern: start with its number of segments, then add 10 for each static segment, 3 for each :param, and subtract 2 for a *. The highest score wins, and on a tie the pattern listed first wins. The function matchPath from exercise 2 is provided.

Exercise 3: pickRoute (starter)
Show hint

score can be a single reduce over the pattern's segments with the number of segments as the start value. In pickRoute, loop over the patterns, skip the ones where matchPath returns null, and replace the current best only when the new score is strictly greater (strict comparison is what makes the first one win a tie).

Show solution
Solution 3: pickRoute

The real scoring uses different numbers (and gives index routes a small bonus), but the idea is identical: static beats dynamic beats splat, and your list order is only a tie-breaker. The stand-in router in the other lessons is simpler on purpose: it takes the first match, which is why its catch-all must come last.

4. A navigation bar that highlights correctly (design)

This navigation bar highlights "Home" on every page, because every URL starts with /. The "Blog" link should stay highlighted on /blog and on /blog/hello-world, and while the page for a clicked link is still loading it should look dimmed. Fix it with NavLink.

JSX
// Nav.jsx - React Router (read-only)
import { NavLink } from 'react-router';

export default function Nav() {
  return (
    <nav>
      <NavLink to="/" className="nav-link">Home</NavLink>
      <NavLink to="/blog" className="nav-link">Blog</NavLink>
      <NavLink to="/about" className="nav-link">About</NavLink>
    </nav>
  );
}
Show hint

NavLink decides "active" by matching its to as a prefix of the current URL, and / is a prefix of everything. There is a prop that switches to exact matching for one link. The className prop also accepts a function that receives { isActive, isPending }; read about it in Link and NavLink.

Show solution
JSX
// Nav.jsx - React Router (read-only)
import { NavLink } from 'react-router';

const linkClass = ({ isActive, isPending }) =>
  ['nav-link', isActive && 'is-active', isPending && 'is-pending'].filter(Boolean).join(' ');

export default function Nav() {
  return (
    <nav>
      <NavLink to="/" end className={linkClass}>Home</NavLink>
      <NavLink to="/blog" className={linkClass}>Blog</NavLink>
      <NavLink to="/about" className={linkClass}>About</NavLink>
    </nav>
  );
}

end makes Home active only on exactly /. Blog needs no end, because the prefix behavior is exactly what you want: /blog/hello-world still belongs to the blog section. NavLink also adds aria-current="page" to the active link by itself, so screen readers announce the current page. Remember that isPending is only ever true with a data router (it needs loaders to be pending); in a plain BrowserRouter app it is always false.

A page at /blog/hello contains <Link to="../tags">. Where does it go? Write resolveTo(from, to), which treats from as a folder and resolves to against it: an absolute to (starting with /) wins, .. removes one segment, . and empty pieces are ignored, and the result never has a trailing slash. This is the behavior you get from relative="path"; React Router's default, route-relative resolution, counts route levels instead of URL segments, which Relative Links and Relative Routing explains.

Exercise 5: resolveTo (starter)
Show hint

Return to immediately if it starts with /. Otherwise keep a stack: from.split('/').filter(Boolean). Loop over to.split('/'): skip '' and '.', pop() for '..' (popping an empty array is harmless, which handles going above the root), and push() anything else. Finish with '/' + stack.join('/').

Show solution
Solution 5: resolveTo

The answer to the opening question is /blog/tags, if the link uses path-relative resolution. With the default route-relative behavior, .. goes up one route: if /blog/hello is rendered by a child route :slug of the blog route, .. leads to the parent route's URL, which is /blog, and ../tags is /blog/tags as well. The two modes only differ when a route's path has several segments, for example a route path="posts/:id/edit" is one level for route-relative .. but three segments for path-relative.

Params

6. A product page that validates its id (design)

The route /products/:id renders <Product />. Write the component so that it reads id from the URL, treats anything that is not a positive whole number (/products/abc, /products/-3, /products/1.5) as "not found", and shows "Product 42" for /products/42. Use useParams, and for the invalid case render a not-found message with a link back to the product list.

Show hint

useParams() always returns strings (or undefined). Convert with Number(id) and check with Number.isInteger(value) && value > 0. Return early from the component for the invalid case, before you use the number for anything else. The lesson on Dynamic Segments explains why a TypeScript type for params does not replace validation.

Show solution
JSX
// Product.jsx - React Router (read-only)
import { Link, useParams } from 'react-router';

export default function Product() {
  const { id } = useParams();
  const productId = Number(id);

  if (!Number.isInteger(productId) || productId <= 0) {
    return (
      <section>
        <h1>Product not found</h1>
        <p>There is no product called "{id}".</p>
        <Link to="/products">Back to all products</Link>
      </section>
    );
  }

  return <h1>Product {productId}</h1>;
}

Number('') is 0, Number('1e3') is 1000 and Number(' 5 ') is 5, so Number alone is lenient; the isInteger and > 0 checks and, if you want strictness, a pattern test such as /^[1-9][0-9]*$/.test(id) close the gaps. Note that this component only decides what to show. In a real app the server must also answer 404 for a valid-looking id that does not exist, which the data-mode lessons cover.

Nesting

7. Trace the nested route branch (logic)

Nested routes mean one URL can mount several components at once: the parent layouts and the leaf page. Write matchBranch(routes, path), which returns the names of the matched routes from the root to the leaf, or null when nothing matches. A route's path can be empty (an index route), a static segment list, or *. A route with children can also match on its own when no child matches the rest of the URL; its Outlet is then simply empty.

Exercise 7: matchBranch (starter)
Show hint

Write a helper walk(routeList, parts) that works on an array of path pieces. For each route: split its path into pieces; if the first piece is *, return [route.name] (the splat takes everything). If its pieces are not a prefix of parts, continue with the next route. Otherwise compute rest. If the route has children, try walk(children, rest) and, on success, return [route.name, ...inner]. After that, if rest is empty, the route matches by itself: return [route.name].

Show solution
Solution 7: matchBranch

The two cases /dashboard and /dashboard/settings show the difference between an index route and a parent matching alone. Dashboard has an index child (Overview), so the empty rest is claimed by that child. Settings has no index child, so /dashboard/settings renders the Settings layout with an empty Outlet, which is usually a sign that you forgot an index route. Each name in the returned list is one Outlet level, which you can picture like this:

flowchart TD
    A["/dashboard/settings/profile"] --> B["Root layout"]
    B -->|Outlet| C["Dashboard layout"]
    C -->|Outlet| D["Settings layout"]
    D -->|Outlet| E["Profile page"]

One URL, four components: each layout renders the next level wherever it places its Outlet.

8. Layouts, an index route and a nested 404 (design)

Design the route tree for this app and write it as JSX:

  • Every page has the same header and footer (one shared layout).
  • /login and /register do not show the header: they use a plain centered card layout.
  • / is the home page.
  • /account is an area with a sidebar. /account itself shows an overview. /account/orders and /account/profile are inner pages.
  • A bad URL under /account (for example /account/billing) shows "not found" inside the account sidebar. Any other bad URL shows a site-wide 404 with the header.
Show hint

You need three kinds of layout routes. The header layout wraps a group of pages and has an element that renders an <Outlet /> but no path (see Layout Routes and Pathless Routes). A pathless route for the card layout can sit next to it. /account is a route with a path, a sidebar element, an index child for the overview and its own path="*" child for the nested 404.

Show solution
JSX
// App.jsx - React Router (read-only)
import { Routes, Route } from 'react-router';

export default function App() {
  return (
    <Routes>
      <Route element={<SiteLayout />}>
        <Route index element={<Home />} />

        <Route path="account" element={<AccountLayout />}>
          <Route index element={<AccountOverview />} />
          <Route path="orders" element={<Orders />} />
          <Route path="profile" element={<Profile />} />
          <Route path="*" element={<AccountNotFound />} />
        </Route>

        <Route path="*" element={<NotFound />} />
      </Route>

      <Route element={<CardLayout />}>
        <Route path="login" element={<Login />} />
        <Route path="register" element={<Register />} />
      </Route>
    </Routes>
  );
}

How the URLs resolve: / gives SiteLayout plus Home. /account/orders gives SiteLayout, AccountLayout and Orders. /account/billing is caught by the nested star, so it renders inside AccountLayout, which keeps the sidebar, while /blog is caught by the outer star and still shows the header from SiteLayout. /login uses CardLayout, so it never gets the header. Neither layout route has a path, so they add no URL segment; they only add structure.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your routes include path='/blog/:slug' and path='/blog/new'. Which one renders for /blog/new?

    React Router ranks routes by specificity, not by source order. A static segment outranks a dynamic one.
  2. 2. A NavLink to='/' is active on every page. What is the fix?

    Active matching is prefix-based and every path starts with /. The end prop limits the match to the exact URL.
  3. 3. What type does useParams give you for an id segment such as /products/42?

    URL segments are text. Convert with Number and check the result before trusting it.
  4. 4. When does a parent route with children match a URL on its own, rendering an empty Outlet?

    The parent's own path matches, so the parent renders. With no child to fill the Outlet, the area stays empty, which usually means an index route is missing.
  5. 5. You want /account/billing to show 'not found' inside the account sidebar. What do you add?

    A star route nested under the account layout only catches URLs below it, and it renders into that layout's Outlet.

Summary

  • The router scores routes by specificity (static, then dynamic, then splat), so the order of sibling routes is only a tie-breaker.
  • matchPath splits both strings into segments and fills a params object. Everything in it is a decoded string.
  • NavLink matches by prefix; add end for exact matching, and use the isActive and isPending callback values for styling.
  • Relative links resolve against the current route (or the current path with relative="path"); .. removes one level.
  • A URL maps to a branch of routes, one Outlet per level, and a parent can match by itself, which usually signals a missing index route.
  • Layout routes without a path share UI without changing URLs, and a nested * route gives a section its own 404.

Next: Exercises: Data Mode