Jonon
Jonon

Reputation: 139

Why aren't components being rendered according to route?

I'm using react router and I have created a route with the path /account which renders the Account component. That component renders a navbar. Below that navbar I want it to render a different component depending on what the URL is. If the URL is account/edit I want to show the edit account component, if the URL is account/myorders I want it to show my orders component and lastly if the URL is account/favorites I want it to show the favorites component below my navbar,

Now I have this problem that the url changes but no component renders below my navbar. if I use exact path on the /account route I get "path does not exist" on the routes /edit, /myorders and /favorites. if I don't use exact on the /account route the same view shows on all routes. Only time when I get a component to render is if I change the route on for example /edit to /.

function Routes() {
  return (
    <Switch>
      <Route path="/" component={Home} exact />

      <Route path="/account" component={Account} />

      <Route render={() => <Route component={Error} />} />
    </Switch>
  );
}

These are my already existing routes that works that are imported into my App.js component

const Account = () => {
  return (
    <Router>
      <NavBar />
      <Switch>
        <Route path="/edit" component={EditAccount} exact />
        <Route path="/myorders" component={MyOrders} />
        <Route path="/favorites" component={Favorites} />
      </Switch>
    </Router>
  );
};

These are the routes in my Account.js component that does not work

Upvotes: 0

Views: 78

Answers (2)

Jonon
Jonon

Reputation: 139

The soloution for me was to use nested routes like this.

const Account = () => {
  let match = useRouteMatch();

  return (
    <Router>
      <NavBar />
      <h1>Account</h1>
      <Switch>
        <Route path={`${match.path}/edit`} component={EditAccount} exact />
        <Route path={`${match.path}/myorders`} component={MyOrders} />
        <Route path={`${match.path}/favorites`} component={Favorites} />
      </Switch>
    </Router>
  );
};

Upvotes: 0

VIVEK JAIN
VIVEK JAIN

Reputation: 116

The problem lies with the fact that you are using <Router></Router> to wrap your routes inside the Acouunt component.

Try to remove that, something like this :-

const Account = () => {
  return (
      <NavBar />
      <Switch>
        <Route path="/edit" component={EditAccount} exact />
        <Route path="/myorders" component={MyOrders} />
        <Route path="/favorites" component={Favorites} />
      </Switch>
  );
};

Check this answer for more info.

Upvotes: 0

Related Questions