React router order of routes, does it matter?

Viewed 716

I set up my react router like this:

<Route exact path="/users">
    <component/>
</Route>
<Route exact path="/users/:id">
    <component/>
</Route>

And it wasn't working correctly (url was changing but content wasn't) after I changed the order of Route in my Routes.js (the one with :id first) it started working. Do it matters or there is other problem somewhere in my code?

3 Answers

Yes you need to check

Route and Switch

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively.

Read and explore more at https://reactrouter.com/web/api/Switch

Yes, nested routes should be above its parent.

So in the following code, about/user has to be above /about. If its beneath then only /about will render

<Route path='about/user' />
<Router path='about/' />

Basic React Router Setup

    <Router>
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
    </Router>
Related