I am running into a scenario where I need to place parameters at the front of the path but am running into a problem using v6.
Suppose I have the following routing:
<Routes>
<Route path='/:companyslug'>
<Route path='home'/>
<Route path='about'/>
<Route path='profile/:id'/>
</Route>
<Route path='/:companyslug/:departmentslug'>
<Route path='home'/>
<Route path='about'/>
<Route path='profile/:id'/>
</Route>
</Routes>
When I try this for example on the following url, https://www.anydomain.com/company1/home, it keeps getting picked up by the /:company/:department route when I need it to be picked up by the /:company route. Is there a specific ordering or other v6 technique that will fix this issue?
2
Answers
That’s because it should be like this:
You’ve already defined the
/:companyslug
route. Anything that needs/:companyslug
shouldn’t be redefined at the same level, it should be nested underneath itIn React Router v6, route matching is determined by the order in which routes are declared.
So, In your example, both /:companyslug and /:companyslug/:departmentslug can match the URL https://www.anydomain.com/company1/home. However, because /:companyslug/:departmentslugis declared after/:companyslug, it takes precedence.
You can reorganize your routes like this: