gotchareactCritical
React : difference between <Route exact path="/" /> and <Route path="/" />
Viewed 0 times
routepathandreactdifferenceexactbetween
Problem
Can someone explain the difference between
and
I don't know the meaning of
and
I don't know the meaning of
exact.Solution
In this example, nothing really. The
For example, imagine we had a
Now the problem here, when we go to
But, if we went to
The
So in this case, we should add
UPDATE 2023 as pointed out by user smit-gabani
The new version of react - v6 does not support exact anymore.
As stated in their documentation:
You don't need to use an exact prop on anymore. This is because all
paths match exactly by default. If you want to match more of the URL
because you have child routes use a trailing * as in
exact param comes into play when you have multiple paths that have similar names:For example, imagine we had a
Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:
Now the problem here, when we go to
http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.But, if we went to
http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!The
exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.So in this case, we should add
exact to our Users route so that it will only match on /users:
UPDATE 2023 as pointed out by user smit-gabani
The new version of react - v6 does not support exact anymore.
As stated in their documentation:
You don't need to use an exact prop on anymore. This is because all
paths match exactly by default. If you want to match more of the URL
because you have child routes use a trailing * as in
Code Snippets
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch><Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>Context
Stack Overflow Q#49162311, score: 550
Revisions (0)
No revisions yet.