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:
/users/123→userId="123"/posts/hello-world→postId="hello-world"/blog/2024/03/my-post→year="2024",month="03",slug="my-post"
File-Based Dynamic Segments
When usingflatRoutes(), prefix segments with $:
$ character is converted to : in the route path.
Accessing Params in Loaders
Access dynamic segments in your loader function:Accessing Params in Components
Use theuseParams 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:Optional Segments
Make segments optional using? (file-based routing):
Splat Routes (Catch-All)
Match all remaining segments using*:
/files/documents/report.pdf→params["*"]="documents/report.pdf"/files/images/2024/photo.jpg→params["*"]="images/2024/photo.jpg"
Escaped Segments (File-Based)
In file-based routing, escape special characters with[]:
$slug[.]json→:slug.json[sitemap.xml]→sitemap.xmlapi[/]v2→api/v2(literal slash)
Data Mutations with Params
Use params in action functions:Navigating with Params
Build dynamic links:Param Constraints and Validation
Validate params in your loader:Best Practices
- Validate params: Always validate dynamic segments in loaders
- Use type inference: Leverage Route.LoaderArgs for type-safe params
- Handle missing data: Throw 404 responses for invalid IDs
- URL encoding: Use
encodeURIComponent()for special characters in params - Keep URLs readable: Use slugs instead of raw IDs when possible
- Document param format: Comment expected param patterns in route files