'React router order of routes, does it matter?
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?
Solution 1:[1]
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
Solution 2:[2]
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/' />
Solution 3:[3]
Basic React Router Setup
<Router>
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prakash S |
Solution 2 | Embedded_Mugs |
Solution 3 | Momin |