Skip to main content

Dynamic Route Segments

Dynamic segments allow routes to match URL patterns with variable parts, enabling you to build routes for user profiles, product pages, blog posts, and more.

Basic Dynamic Segments

Define dynamic segments with a colon (:) prefix in manual configuration:
Matches:
  • /users/123userId = "123"
  • /posts/hello-worldpostId = "hello-world"
  • /blog/2024/03/my-postyear = "2024", month = "03", slug = "my-post"

File-Based Dynamic Segments

When using flatRoutes(), prefix segments with $:
The $ character is converted to : in the route path.

Accessing Params in Loaders

Access dynamic segments in your loader function:

Accessing Params in Components

Use the useParams hook in your component:

Type-Safe Params

React Router provides automatic type inference for params:

Multiple Dynamic Segments

Combine multiple dynamic segments in a single route:

Nested Dynamic Segments

Dynamic segments work seamlessly with nested routes:
Child routes inherit parent params:

Optional Segments

Make segments optional using ? (file-based routing):
Or in manual config:

Splat Routes (Catch-All)

Match all remaining segments using *:
Access the matched segments:
Matches:
  • /files/documents/report.pdfparams["*"] = "documents/report.pdf"
  • /files/images/2024/photo.jpgparams["*"] = "images/2024/photo.jpg"

Escaped Segments (File-Based)

In file-based routing, escape special characters with []:
Examples:
  • $slug[.]json:slug.json
  • [sitemap.xml]sitemap.xml
  • api[/]v2api/v2 (literal slash)

Data Mutations with Params

Use params in action functions:
Build dynamic links:
Or use the navigate function:

Param Constraints and Validation

Validate params in your loader:

Best Practices

  1. Validate params: Always validate dynamic segments in loaders
  2. Use type inference: Leverage Route.LoaderArgs for type-safe params
  3. Handle missing data: Throw 404 responses for invalid IDs
  4. URL encoding: Use encodeURIComponent() for special characters in params
  5. Keep URLs readable: Use slugs instead of raw IDs when possible
  6. Document param format: Comment expected param patterns in route files

Common Patterns

User Profile

Blog Post

E-commerce Product

Date-based Archive

File Browser