Search code examples
javascriptreactjsreact-routerreact-router-domreact-router-redux

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,

  • Edit Account
  • My Orders
  • Favorites

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


Solution

  • 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>
      );
    };