react-router render menu when path does not match

If you don't wish to use Regular Expressions directly, you can place your login Route in a Switch with the top menu component Route. It will only run the first matching Route and routes without a path attribute match anything.

<div>
    <Switch>
      <Route
          exact path="/"
          render={props => (
              <LoginContainer {...props} setTitle={this.setTitle} />
          )}
      />
      <Route path="/:subpath" component={TopMenuComponent} />
    </Switch>           
    <Route path='/landing' component={LandingComponent} />
</div>

For your example, you would need to reorder your divs.


Regex in the route path didn't work for me. What worked for me was this. Just add the other condition.

 <Route render={({ location }) => {
     return location.pathname.indexOf('/login') === -1 ? TopMenuComponent : null 
  }} />

Simplest Implementation

Use a ternary expression or short-circuit evaluation to conditionally render your component based on location.pathname, like so:

<Route 
    render={({ location }) => ['/', '/login'].includes(location.pathname)
        ? <Component/>
        : null
    }
/>

Regex Implementation

React Router's matching of path strings relies on path-to-regexp@^1.7.0.

As a result, you can instruct routes to not render for certain paths using regular expressions.

The following implementations should render given any path value, bar "/" and "/login":

// With Regex Inside String.
<Route path={"^(?!.*(\/|\/login)).*$"} component={TopMenuComponent}/>

// With Explicit Regex.
<Route path={new RegExp('^(?!.*(\/|\/login)).*$')} component={TopMenuComponent}/>

Tags:

React Router