Red Baron
Red Baron

Reputation: 7682

How do I conditionally render a navbar in react-router?

How can I conditionally render a nav bar in React Router 5? so far I've got this in my <Router>

{window.location.href.includes('data-url') ? null : (
    <CONNECTED_NAV />
)}

which does work but with one issue. I have a link in my data-url component which redirects back to the app. but once it redirects back and lands on another route /home then the nav bar is still not showing and I've consoled logged in the <Router> component and it's not re-rendering so that's why it's not showing.

is there a better way to force an update? or how to conditionally render a navbar?

Upvotes: 0

Views: 1771

Answers (2)

codingwithmanny
codingwithmanny

Reputation: 1184

Just expanding on @ahmad-nawaz-khan solution

You may still want to pass in the router props from react-router

<Route exact path="/home" render={(routerProps) => (condition ? <CONNECTED_NAV {...routerProps} /> : null)} />

Upvotes: 1

Ahmad Nawaz Khan
Ahmad Nawaz Khan

Reputation: 127

If you want your navbar to show up on the /home page only then you have to specify a route:

<Route exact path="/home" component={CONNECTED_NAV} />

This way the navbar will be only visible when the URL matches /home

But if you want to show the navbar conditionaly on the homepage then you can also do that by replacing component with render

<Route exact path="/home" render={() => (condition ? <CONNECTED_NAV /> : null)} />

Route must be wrapped in BrowserRouter if you don't know about these maybe please visit React Router

Upvotes: 1

Related Questions