Replies: 3 comments 1 reply
-
|
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
// Check if a string matches any registered route
const match = router.matchRoute('/users/123')
if (match) {
// /users/123 matches /users/$id
}
const noMatch = router.matchRoute('/blah')
// noMatch is undefined — no registered route matchesYou can also get the matched params: const match = router.matchRoute('/users/123', { getParams: true })
// match.route — the route definition
// match.params — { id: '123' }If you just need to check a pattern without a full router instance, there's import { matchPathname } from '@tanstack/react-router'
// Check a specific path against a pattern
const result = matchPathname({ path: '/users/123', pattern: '/users/$id' })
// result — { match: true, params: { id: '123' } }
|
Beta Was this translation helpful? Give feedback.
-
|
Ah, you're right — in current v1.x function isValidRoute(path: string): boolean {
const match = router.matchRoute(path)
return match !== null && typeof match === 'object' && 'route' in match
}Or use router.matchRoutes('/users/123').length > 0Cleanest approach without relying on the empty-object behavior: import { matchPathname } from '@tanstack/react-router'
function pathMatchesAnyRoute(path: string): boolean {
return Object.values(router.routesById).some(route => {
if (!route.options.path) return false
return matchPathname({ path, pattern: route.options.path }).match
})
} |
Beta Was this translation helpful? Give feedback.
-
|
Use function pathMatchesAnyRoute(router, path: string): boolean {
const matches = router.matchRoutes(path)
const leaf = matches[matches.length - 1]
return !!leaf && leaf.routeId !== '__root__'
}With routes pathMatchesAnyRoute(router, '/users/123') // true -> matches /users/$id
pathMatchesAnyRoute(router, '/users') // true
pathMatchesAnyRoute(router, '/dashboard') // true
pathMatchesAnyRoute(router, '/blah') // false
pathMatchesAnyRoute(router, '/user/123') // false (typo'd segment)Why not
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a string value and I want to check if it matches a route pattern that's registered in the router. I'm looking for a true/false response so I can then do something with it.
An example of this is does
/users/123match any of/,/dashboard,/users,/users/$idetc. that have been registered in my route tree. The value being checked could also beblahor/user/123, either way I want to know if a string of some value matches any registered route.I've searched all over but can't find anything talking about how to check if an arbitrary value matches a route pattern. I've seen various examples of checking routes but none show how to check an unknown value against all routes.
Beta Was this translation helpful? Give feedback.
All reactions