Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide header component in react-router-dom?

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>
        &copy; Acme Inc. 2017
      </footer>
    </div>
  </Router>
);
like image 455
Sivadass N Avatar asked Oct 25 '17 18:10

Sivadass N


2 Answers

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>
        &copy; Acme Inc. 2017
      </footer>
    </div>
  </Router>
)
};


export default withRouter(App);
like image 98
Gulam Hussain Avatar answered Sep 21 '22 18:09

Gulam Hussain


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

like image 42
Vorcan Avatar answered Sep 22 '22 18:09

Vorcan