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
Taken Regex from Arman's answer.
const notInLogin = /^(?!.*(\/login)).*$/
export default () => (
<Router history={history}>
<>
<Route path={notInLogin} component={NavBar} />
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/accounts" component={Account} />
<Route exact path="/profile" component={Profile} />
<Route exact path="/" component={Home} />
</Switch>
</>
</Router>
)
If you get PropsType error: https://stackoverflow.com/a/50439120/1099314
Similar to taylor michels answer, but the following accounts for both the '/login' and the '/' (root) routes:
<Route
render={({ location }) =>
location.pathname !== "/" && location.pathname !== "/login" ? (
<TopMenuComponent />
) : null
}
/>>
This also renders the component as a jsx tag <TopMenuComponent />
, which works for me where the other approach did not.
You can use useRouteMatch hook
const ParentComponent = props => {
const matched = useRouteMatch(['/', '/login'])
if (matched && matched.isExact) return null
return <ChildComponent {...props} />
}
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
}} />
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}/>
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.