Reputation: 3727
Is there a way to define a dynamic route with fixed set of values? And if it doesn't fit any of the fixed values it would fallback to the next route. My current is like this -
const routes = {
path: '',
component: AppComponent,
childRoutes: [
{ path: '/search/top', name: 'top', component: FixedSearchComponent},
{ path: '/search/new', name: 'new', component: FixedSearchComponent},
{ path: '/search', name: 'search', component: SearchComponent},
{ path: '/search/:query', name: 'search', component: SearchComponent},
]
}
But I'd like to define a parameter for it like :fixedSearch
maybe and have it predefined to only be this values. Maybe something like this? And if it doesn't fit any of top
or new
(or other possible set), it would fallback to search
.
const routes = {
path: '',
component: AppComponent,
childRoutes: [
{ path: '/search/:fixedSearch', name: 'fixedSearch', fixedSearch: ['top', 'new'], component: FixedSearchComponent},
{ path: '/search', name: 'search', component: SearchComponent},
{ path: '/search/:query', name: 'search', component: SearchComponent},
]
}
Upvotes: 1
Views: 1006
Reputation: 381
You could attach an onEnter
function a new route, like /fixed/:fixedSearch
that replaces /search/new
and /search/top
. Inside the onEnter
function you would compare :fixedSearch
to your predefined values (['top', 'new']
) and if they don't match you can fallback to your /search
route. This is common for checking if a user is authenticated before allowing access to a route.
Here's the documentation for onEnter
:
onEnter(nextState, replace, callback?)
Called when a route is about to be entered. It provides the next router state and a function to redirect to another path. this will be the route instance that triggered the hook.
If callback is listed as a 3rd argument, this hook will run asynchronously, and the transition will block until callback is called.
A rough example (in JSX) might look like:
<Route path='/fixed/:fixedSearch' component={FixedSearchComponent} onEnter={checkFixedSearch} />
function checkFixedSearch(nextState, replace) {
if (*Compare :fixedSearch with predefined values*) {
replace('/search') // move to search route if fixed values don't match
}
}
Upvotes: 1