Reputation: 95
I want to making conditional Header
page by page, which means that I don't want to show Header
at Home
page and I want to show Header
at the other pages like posts page, projects page, etc..
I've tried to think how can I solved this problem, but there was no special way to working with react-router-dom
. Of course, it may be only hard for me.
Whatever, I can't solve above problem is same.
So, this is current code:
<div className="ui container">
<BrowserRouter>
<Header />
<Route exact path="/">
<Route exact path="/posts">
<Route exact path="/project">
<Route exact path="/profile">
</BrowserRouter>
</div>
and I want fix it like this:
<div className="ui container">
<BrowserRouter>
{() => {
if(path !=="/")
return <Header />;
} else {
return ;
}}
<Route exact path="/">
<Route exact path="/posts">
<Route exact path="/project">
<Route exact path="/profile">
</BrowserRouter>
</div>
Upvotes: 2
Views: 4303
Reputation: 366
without Switch , you can do this :
<BrowserRouter>
{window.location.pathname !== "/" ? <Header /> : null}
<Route exact path="/">
<Route exact path="/posts">
<Route exact path="/project">
<Route exact path="/profile">
</BrowserRouter>
Upvotes: 4
Reputation: 52
There are ways you can do it.
You can use withRouter(), an Higher Order Component to wrap your component. So, with that that component will have access to the BrowserRouter props.
You can use Redux, We the posts page/component is mounted you set a isheader state to false. then you can use this state to condition the Header component.
A reference link:- Hide header on some pages in react-router-dom
Another method is to wrap those route that will have the header with a parent component example:
const Layout = ({ children }) => (
<div>
<Header />
{children}
</div>
)
const App = ()=> (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Layout>
<Route exact path="/posts" component={..}>
<Route exact path="/project" component={..}>
<Route exact path="/profile" component={..}>
</Layout>
</Switch>
</BrowserRouter>
)
Upvotes: 1
Reputation: 506
try with a Switch
:
import { Route, Switch } from 'react-router-dom';
...
<Switch>
<Route exact path="/" component={null} />
<Route component={Header} />
<Switch>
...
doc: https://reacttraining.com/react-router/web/api/Switch
Upvotes: 1