Skip to content

Routes in React Router

Routes connect URL paths to React components. This lesson covers path syntax, index routes, optional segments, splats, and organizing route definitions as your app grows.

Defining Routes

Each <Route> maps a path pattern to an element (React node). The first match wins within <Routes>. Use index routes for default child content at a parent path.

Route objects via createBrowserRouter offer data APIs and centralized configuration — popular in larger apps.

<Routes>
  <Route path="/" element={<Layout />}>
    <Route index element={<Home />} />
    <Route path="products" element={<Products />} />
    <Route path="products/:id" element={<ProductDetail />} />
    <Route path="*" element={<NotFound />} />
  </Route>
</Routes>

* catch-all route handles 404 pages.

Path Pattern Syntax

/users/:userId        // dynamic segment
/files/*              // splat (rest of path)
/settings/:tab?       // optional (v6.4+ optional params)
index                 // default child at parent path
  • Dynamic segments become available via useParams().
  • Index routes render at parent's path without extra segment.
  • Catch-all * route should be last.
  • Relative paths in nested routes append to parent.

Route Path Patterns

Common URL patterns in React Router.

Pattern Matches
/about Exact /about
/users/:id /users/42 → id=42
/docs/* /docs/a/b rest splat
index Parent path exactly
* Any unmatched path
Relative team Nested under parent path

createBrowserRouter

Data routers define routes as objects with loader, action, and errorElement for data-driven routing — common in React Router v6.4+ and v7 frameworks.

const router = createBrowserRouter([
  { path: '/', element: <Layout />, children: [
    { index: true, element: <Home /> },
    { path: 'about', element: <About /> },
  ]},
]);

Lazy Route Components

Combine React.lazy with route element for code splitting per page — covered in the Lazy Loading lesson.

Common Mistakes

  • Absolute paths in nested routes breaking hierarchy.
  • Missing catch-all 404 route.
  • Duplicate paths causing unexpected matches.
  • Forgetting index route leaving parent layout empty at /.

Key Takeaways

  • Routes map paths to elements with optional nesting.
  • Dynamic segments use :param syntax.
  • Index routes fill parent default; * catches 404s.
  • Consider createBrowserRouter for large route tables.

Pro Tip

Generate typed route paths with const objects — ROUTES.product(id) — to avoid typos in links.