user1354934
user1354934

Reputation: 8851

React router only show Navigation component if the current path is on any of the valid routes

For a invalid route, I want to show the NotFound component, but also not show the Navigation component:

const Layout: React.FunctionComponent = () => {
  return (
    <Router>
      <Navigation />
      <Switch>
        <Route path="/explore" exact>
          <ExploreIndex />
        </Route>
        <Route path="/explore/:id" exact>
          <ExploreShow />
        </Route>
        <Route path="/" exact>
          <Home />
        </Route>

        <Route component={NotFound} />
      </Switch>
    </Router>
  );
};

If I go to /aaaaaaa, my NotFound component loads but so does my Navigation. How can I not have Navigation render for such routes?

Upvotes: 2

Views: 487

Answers (2)

kind user
kind user

Reputation: 41913

What about just rendering it as another route?

<Route path={['/explore', '/explore/:id', '/']} exact component={Navigation} />

It will not be rendered if the route does not match any of the routes listed in the path array.

Upvotes: 2

ertemishakk
ertemishakk

Reputation: 547

You can add NavigationBar in the specific components rather than app.js. So for example if there is a about page, place NavigationBar on top of the component

Upvotes: 0

Related Questions