Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router render menu when path does not match

Tags:

I'm using react-router and I want to render a menu component when the user is not in the root and not in the /login path. This is what I have so far

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

takes care of not rendering the TopMenuComponent component in the '/' location, however how do I avoid it rendering TopMenuComponent when the user is in the /login path? I could always create another component and wrap it up, but I think that is too much just for this.

like image 628
tmp dev Avatar asked Oct 19 '17 05:10

tmp dev


People also ask

Why is match undefined react router?

react-router-dom v5 If using RRDv5 if the match prop is undefined this means that BookScreen isn't receiving the route props that are injected when a component is rendered on the Route component's component prop, or the render or children prop functions.

How do I get past pathname in react router?

To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value.


2 Answers

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}/> 
like image 125
Arman Charan Avatar answered Sep 20 '22 20:09

Arman Charan


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    }} /> 
like image 21
taylor michels Avatar answered Sep 19 '22 20:09

taylor michels