Reputation: 270
In my react app, there is a common header which is outside of my Routes and other components are loaded based on routing.
<React.Fragment>
<Header />
<div className="container dflex">
<Switch>
<Route path="/money-transfer" component={MoneyTransfer} />
<Redirect from="/" to="/money-transfer" exact />
<Route path="/dmt" exact component={MyDmt} />
<Route component={NoFound} />
</Switch>
</div>
</React.Fragment>
I want to also hide my header when NoFound Page is rendered. What can be the best possible solution for this ?
Upvotes: 2
Views: 471
Reputation: 413
Try this,
<React.Fragment>
let HideHeader = NoFound ? null : <Header />
{HideHeader}
<div className="container dflex">
<Switch>
<Route path="/money-transfer" component={MoneyTransfer} />
<Redirect from="/" to="/money-transfer" exact />
<Route path="/dmt" exact component={MyDmt} />
<Route component={NoFound} />
</Switch>
</div>
</React.Fragment>
Upvotes: 1
Reputation: 11257
You could Redirect
to a particular route when no route is matched and then check for that route in Header
to hide that component.
<Switch>
<Route path="/money-transfer" component={MoneyTransfer} />
<Redirect from="/" to="/money-transfer" exact />
<Route path="/dmt" exact component={MyDmt} />
<Route component={NoFound} />
</Switch>
function NoFound() {
return <Redirect to="/notfound" />;
}
// Header.js
const Header = props => {
const { location } = props;
if (location.pathname.match(/notfound/)) {
return <NotFoundRoute />;
}
return <h3>I am the Header</h3>;
};
export default withRouter(Header);
// NotFoundRoute.js
function NotFoundRoute() {
return <div>No Route Found</div>;
}
Working code sample codesandbox link
Hope that helps!!!
Upvotes: 2