本页还没有译文
本页 169 段还没译成Deutsch,下面显示的是英文原文。Path Params
还没翻译译自英文(tanstack.com)本页 169 段都还没译
Path params are used to match a single segment (the text until the next /) and provide its value back to you as a named variable. They are defined by using the $ character prefix in the path, followed by the key variable to assign it to. The following are valid path param paths:
$postId$name$teamIdabout/$nameteam/$teamIdblog/$postId
Because path param routes only match to the next /, child routes can be created to continue expressing hierarchy:
Let's create a post route file that uses a path param to match the post ID:
Path Params can be used by child routes
Once a path param has been parsed, it is available to all child routes. This means that if we define a child route to our postRoute, we can use the postId variable from the URL in the child route's path!
Path Params in Loaders
Path params are passed to the loader as a params object. The keys of this object are the names of the path params, and the values are the values that were parsed out of the actual URL path. For example, if we were to visit the /blog/123 URL, the params object would be { postId: '123' }:
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
return fetchPost(params.postId)
},
})The params object is also passed to the beforeLoad option:
export const Route = createFileRoute('/posts/$postId')({
beforeLoad: async ({ params }) => {
// do something with params.postId
},
})Path Params in Components
If we add a component to our postRoute, we can access the postId variable from the URL by using the route's useParams hook:
🧠 Quick tip: If your component is code-split, you can use the getRouteApi function to avoid having to import the
Routeconfiguration to get access to the typeduseParams()hook.
Path Params outside of Routes
You can also use the globally exported useParams hook to access any parsed path params from any component in your app. You'll need to pass the strict: false option to useParams, denoting that you want to access the params from an ambiguous location:
Prioritizing Parsed Path Param Routes
When multiple dynamic, optional, or wildcard routes can match the same URL, routes with params.parse are tried before equivalent routes without it. If multiple matching candidates use params.parse, you can use params.priority to control which candidate is tried first.
Higher params.priority values are tried first. The default priority is 0, and if a higher-priority route's params.parse returns false, matching continues to the next candidate route.
params.parse runs during route planning and may be evaluated more than once.
It must be deterministic and side-effect-free for the same raw params.
export const Route = createFileRoute('/posts/$postId')({
params: {
priority: 10,
parse: ({ postId }) => {
if (!/^\d+$/.test(postId)) return false
return { postId: Number(postId) }
},
stringify: ({ postId }) => ({ postId: String(postId) }),
},
})With a fallback /posts/$slug route, /posts/123 can match the parsed numeric route first, while /posts/hello-world can fall through to the slug route when params.parse returns false.
params.priority only affects competing candidates that use params.parse. It does not override normal route specificity, so static routes still match before dynamic, optional, or wildcard routes.
Navigating with Path Params
When navigating to a route with path params, TypeScript will require you to pass the params either as an object or as a function that returns an object of params.
Let's see what an object style looks like:
function Component() {
return (
<Link to="/blog/$postId" params={{ postId: '123' }}>
Post 123
</Link>
)
}And here's what a function style looks like:
function Component() {
return (
<Link to="/blog/$postId" params={(prev) => ({ ...prev, postId: '123' })}>
Post 123
</Link>
)
}Notice that the function style is useful when you need to persist params that are already in the URL for other routes. This is because the function style will receive the current params as an argument, allowing you to modify them as needed and return the final params object.
Prefixes and Suffixes for Path Params
You can also use prefixes and suffixes with path params to create more complex routing patterns. This allows you to match specific URL structures while still capturing the dynamic segments.
When using either prefixes or suffixes, you can define them by wrapping the path param in curly braces {} and placing the prefix or suffix before or after the variable name.
Defining Prefixes
Prefixes are defined by placing the prefix text outside the curly braces before the variable name. For example, if you want to match a URL that starts with post- followed by a post ID, you can define it like this:
You can even combine prefixes with wildcard routes to create more complex patterns:
Defining Suffixes
Suffixes are defined by placing the suffix text outside the curly braces after the variable name. For example, if you want to match a URL a filename that ends with txt, you can define it like this:
You can also combine suffixes with wildcards for more complex routing patterns:
Combining Prefixes and Suffixes
You can combine both prefixes and suffixes to create very specific routing patterns. For example, if you want to match a URL that starts with user- and ends with .json, you can define it like this:
Similar to the previous examples, you can also use wildcards with prefixes and suffixes. Go wild!
Optional Path Parameters
Optional path parameters allow you to define route segments that may or may not be present in the URL. They use the {-$paramName} syntax and provide flexible routing patterns where certain parameters are optional.
Defining Optional Parameters
Optional path parameters are defined using curly braces with a dash prefix: {-$paramName}
// Single optional parameter
// src/routes/posts/{-$category}.tsx
export const Route = createFileRoute('/posts/{-$category}')({
component: PostsComponent,
})
// Multiple optional parameters
// src/routes/posts/{-$category}/{-$slug}.tsx
export const Route = createFileRoute('/posts/{-$category}/{-$slug}')({
component: PostComponent,
})
// Mixed required and optional parameters
// src/routes/users/$id/{-$tab}.tsx
export const Route = createFileRoute('/users/$id/{-$tab}')({
component: UserComponent,
})How Optional Parameters Work
Optional parameters create flexible URL patterns:
/posts/{-$category}matches both/postsand/posts/tech/posts/{-$category}/{-$slug}matches/posts,/posts/tech, and/posts/tech/hello-world/users/$id/{-$tab}matches/users/123and/users/123/settings
When an optional parameter is not present in the URL, its value will be undefined in your route handlers and components.
Accessing Optional Parameters
Optional parameters work exactly like regular parameters in your components, but their values may be undefined:
Optional Parameters in Loaders
Optional parameters are available in loaders and may be undefined:
export const Route = createFileRoute('/posts/{-$category}')({
loader: async ({ params }) => {
// params.category might be undefined
return fetchPosts({ category: params.category })
},
})Optional Parameters in beforeLoad
Optional parameters work in beforeLoad handlers as well:
export const Route = createFileRoute('/posts/{-$category}')({
beforeLoad: async ({ params }) => {
if (params.category) {
// Validate category exists
await validateCategory(params.category)
}
},
})Advanced Optional Parameter Patterns
With Prefix and Suffix
Optional parameters support prefix and suffix patterns:
All Optional Parameters
You can create routes where all parameters are optional:
Optional Parameters with Wildcards
Optional parameters can be combined with wildcards for complex routing patterns:
Navigating with Optional Parameters
When navigating to routes with optional parameters, you have fine-grained control over which parameters to include:
function Navigation() {
return (
<div>
{/* Navigate with optional parameter */}
<Link to="/posts/{-$category}" params={{ category: 'tech' }}>
Tech Posts
</Link>
{/* Navigate without optional parameter */}
<Link to="/posts/{-$category}" params={{ category: undefined }}>
All Posts
</Link>
{/* Navigate with multiple optional parameters */}
<Link
to="/posts/{-$category}/{-$slug}"
params={{ category: 'tech', slug: 'react-tips' }}
>
Specific Post
</Link>
</div>
)
}Type Safety with Optional Parameters
TypeScript provides full type safety for optional parameters:
Internationalization (i18n) with Optional Path Parameters
Optional path parameters are excellent for implementing internationalization (i18n) routing patterns. You can use prefix patterns to handle multiple languages while maintaining clean, SEO-friendly URLs.
Prefix-based i18n
Use optional language prefixes to support URLs like /en/about, /fr/about, or just /about (default language):
This pattern matches:
/about(default locale)/en/about(explicit English)/fr/about(French)/es/about(Spanish)
Complex i18n Patterns
Combine optional parameters for more sophisticated i18n routing:
This supports URLs like:
/blog/tech/my-post(default locale, tech category)/fr/blog/my-post(French, no category)/en/blog/tech/my-post(explicit English, tech category)/es/blog/tecnologia/mi-post(Spanish, Spanish category)
Language Navigation
Create language switchers using optional i18n parameters with function-style params:
You can also create more sophisticated language switching logic:
Advanced i18n with Optional Parameters
Organize i18n routes using optional parameters for flexible locale handling:
SEO and Canonical URLs
Handle SEO for i18n routes properly:
Type Safety for i18n
Ensure type safety for your i18n implementations:
Optional path parameters provide a powerful and flexible foundation for implementing internationalization in your TanStack Router applications. Whether you prefer prefix-based or combined approaches, you can create clean, SEO-friendly URLs while maintaining excellent developer experience and type safety.
Allowed Characters
By default, path params are escaped with encodeURIComponent. If you want to allow other valid URI characters (e.g. @ or +), you can specify that in your RouterOptions.
Example usage:
const router = createRouter({
// ...
pathParamsAllowedCharacters: ['@'],
})This setting is fixed when the router is created. To use different allowed characters, create a new router instance.
The following is the list of accepted allowed characters:
;:@&=+$,