react router changes url but not navigating to page

Viewed 585

I am having trouble in changing the page in react with react-router-dom. here is my router :-

import { Route, Switch, BrowserRouter } from 'react-router-dom';
import HomePage from '../pages/grocery';
import Profile from '../pages/profile';
import CheckoutPage from '../pages/checkout';
export default function Routes(props) {
  return (
      <BrowserRouter>
        <Switch>
          <Route path="/" name="Home" component={HomePage} exact />
          <Route path="/profile" name="Profile" component={Profile} />
          <Route path="/checkout" name="Checkout" component={CheckoutPage} />
        </Switch>
    </BrowserRouter>

  );
}

and here is my Link tag

<Link to="/profile">Profile</Link>
1 Answers

the problem here is that the second Route element, have a "/" too, and the first one will access any element that starts with an "/". How to fix this? with Route you can put "exact" just before path, so it will only access that specific route, no matters what comes after that. example:

<Route exact path="/" name="Home" component={HomePage} />
<Route exact path="/profile" name="Profile" component={Profile} />
<Route exact path="/checkout" name="Checkout" component={CheckoutPage} />

this way you will not have problems accessing your others pages or components.

Related