skip to Main Content

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


  1. That’s because it should be like this:

    <Routes>
        <Route path='/:companyslug'>
            <Route path='home'/>
            <Route path='about'/>
            <Route path='profile/:id'/>
            <Route path='/:departmentslug'>
                <Route path='home'/>
                <Route path='about'/>
                <Route path='profile/:id'/>
            </Route>
        </Route>
    </Routes>
    

    You’ve already defined the /:companyslug route. Anything that needs /:companyslug shouldn’t be redefined at the same level, it should be nested underneath it

    Login or Signup to reply.
  2. In 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:

    <Routes>
    <Route path='/:companyslug/:departmentslug'>
        <Route path='home'/>
        <Route path='about'/>
        <Route path='profile/:id'/>
    </Route>
    <Route path='/:companyslug'>
        <Route path='home'/>
        <Route path='about'/>
        <Route path='profile/:id'/>
    </Route>
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search