I am having a React app like this one here I want to hide the global header component from page like Login and Signup. I can't find any approach for this in React-Router-v4 over internet. Could anybody please shed some light on me to proceed further?
const App = () => (
<Router>
<div className="app-wrapper">
<Header />
<main>
<Route path="/" exact component={Home} />
<Route path="/login" exact component={Login} />
<Route path="/contact" component={Contact} />
</main>
<footer>
© Acme Inc. 2017
</footer>
</div>
</Router>
);
You can use withRouter
Higher Order component to access props.location
object in your App component and check if user is on login or signup page using props.location.pathname
keep in mind that you don't have to use withRouter
component if your component in which you want to access props.match
or props.location
object is rendered by <Route/>
import {Route, withRouter} from 'react-router-dom'
const App = (props) => {
return(
<Router>
<div className="app-wrapper">
{
props.location.pathname!=='/login' ? <Header/>:null
}
<main>
<Route path="/" exact component={Home} />
<Route path="/login" exact component={Login} />
<Route path="/contact" component={Contact} />
</main>
<footer>
© Acme Inc. 2017
</footer>
</div>
</Router>
)
};
export default withRouter(App);
If you simply want to hide/show the header based on the authorization status, then you can pass an object containing the authorization status to the Header component based on which it will render the menu items.
I've forked the demo here: https://codesandbox.io/s/pjyl9y17rx
Here I'm just passing a boolean value for authorization status, but you get the idea.
The other option to render a route based on the path is to use a regex in the path, which I believe is supported, going by this conversation: https://github.com/ReactTraining/react-router/issues/391
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