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.
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.
To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value.
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 } />
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}/>
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 }} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With