why two routes calling same page in react js that has different path link

Viewed 155

<Route path={${process.env.PUBLIC_URL}/book-repair/:name/:name} component={Modals}/> <Route path={${process.env.PUBLIC_URL}/book-repair/:name} component={Companies}/>

when call second route this is calling very well. but when am call first route first route and second route both are calling. please solve my issue.

3 Answers

Use Switch to render the Routes Exclusively and use exact to strictly match the pattern

import { Route, Switch } from "react-router";

let routes = (
  <Switch>
    <Route path={${process.env.PUBLIC_URL}/book-repair/:name/:name} component={Modals} exact />
    <Route path={${process.env.PUBLIC_URL}/book-repair/:name} component={Companies} exact />
  </Switch>
);

Refer: https://reactrouter.com/web/api/Switch

    <Switch><Route path={${process.env.PUBLIC_URL}/book-repair/:name/:name} exact component={Modals}/> 
<Route path={${process.env.PUBLIC_URL}/book-repair/:name} exact component={Companies}/> </Switch>

You should add exact and Switch to your routes.

If you are rendering the routes into a Router they both can be matched and rendered. The Router inclusivley matches and renders routes. Use the exact prop to exactly match one or the other. The issue is that ${process.env.PUBLIC_URL}/book-repair/:name is a prefix for ${process.env.PUBLIC_URL}/book-repair/:name/:name, and so will also be matched.

<Route
  exact
  path={`${process.env.PUBLIC_URL}/book-repair/:name/:name`}
  component={Modals}
/>
<Route
  exact
  path={`${process.env.PUBLIC_URL}/book-repair/:name`}
  component={Companies}
/>

The alternative is to render the routes into a Switch to exclusively match and render routes. Here path order and specificity matter. Order your routes from most specific to least specific. You don't need to specify the exact prop since the Switch only matches and renders the first matching Route.

<Switch>
  ...
  <Route
    path={`${process.env.PUBLIC_URL}/book-repair/:name/:name`}
    component={Modals}
  />
  <Route
    path={`${process.env.PUBLIC_URL}/book-repair/:name`}
    component={Companies}
  />
  ...
</Switch>
Related