Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent matching two routes with react-router v4?

I have the following two routes: /items and /items/buy.

Each route corresponds to a Tab in a single view. Both routes are rendered with an exact prop, but still, two tabs are being marked as active when navigating to /items/buy.

I already tried using withRouter, but I noticed changing /items to /items/sell fixes the problem, but I don't wanna have that route.

I understand rrv4 is matching the first part of my route /items and the other route too /items/buy, but I think that shouldn't be happening if I'm using exact. Any clues on why this is happening?

Ahh I forgot to say I am already using a Switch.

Thanks for your help!

like image 343
Whee Avatar asked Jul 06 '17 21:07

Whee


People also ask

How do I restrict routes in react router?

The Route component from react-router is public by default but we can build upon it to make it restricted. We can add a restricted prop with a default value of false and use the condition if the user is authenticated and the route is restricted, then we redirect the user back to the Dashboard component.

How can I ensure a route matches only if the complete path matches?

If the intention is to strictly match only /items , the <Route/> component accepts an exact prop. Adding this ensures that only the pathname that exactly matches the current location is rendered. Below is an example that uses the exact prop.

How do you protect a route in react?

In your application, create Protected.export default Protected; In this component, the if statement is used to check whether the user is authenticated. If they are not, Navigate from react-router-dom redirects them to the home page. However, if the user is authenticated, the child component is rendered.

Which props should you use to match exactly the path you have for routing?

pathname will match exact location path.


1 Answers

You need to put your routes in a <Switch> component. The switch will only render the first route that matches.

import {Route, Switch} from 'react-router-dom';

<Switch>
  <Route exact path="/" component={Main} />
  <Route exact path="/items" component={SomeComponent} />
  <Route exact path="/items/buy" component={SomeOtherComponent} />
  <Route component={NotFound} />
</Switch>
like image 156
Milenko Avatar answered Sep 28 '22 23:09

Milenko