How to hide header component in login page reactJS

11,254

Solution 1

In the render method of your HeaderNavContainer, you can do this:

render() {
  if (window.location.pathname === '/EmployeeLogin') return null;
  return <insert your header nav code>;
}

Since HeaderNavContainer is wrapped within <Router>, it'll re-render when window.location.pathname changes.

Alternatively, add HeaderNavContainer to your About, MyPreferences etc instead of putting in App.

Solution 2

In component you can check if the history.location.pathname is equal to /EmployeeLogin and then return null. You can use withReducer for getting history object as a prop.

render(){
  if(this.props.history.location.pathname==='/EmployeeLogin'){
    return null;
  }   
  return (//your navigation component code.)
}

Solution 3

Instead of checking component exists or not try to check the URL is hit or not

In window.location.pathname you will get the current URL.

let HideHeader = window.location.pathname === 'your need string' ? null :

Share:
11,254
Prashanth Harish
Author by

Prashanth Harish

Hi am UI/UX developer of web. Am good in Angular JS, JavaScript, JQuery, HTML, CSS, Bootstrap, PHP, Adobe Photoshop etc.,

Updated on July 30, 2022

Comments

  • Prashanth Harish
    Prashanth Harish almost 2 years

    Am new to ReactJS. I want to hide header component in Login page and show in inner pages. I have an App.js I have used ternary operator but not working.

    class App extends Component {
        render(){
        let HideHeader = EmployeeLogin ? null : <HeaderNavContainer />
            return (
                <div>
                    <Router history={history}>
                        <div>                    
                            {HideHeader}
                            <Switch>
                                <Route path="/about" component={About} />
                                <Route path="/EmployeeLogin" component={EmployeeLogin} />                        
                                <Route path="/MyPreferences" component={MyPreferences} />                        
                                <Route component={PageNotFound} />
                            </Switch>    
                        </div>    
                    </Router>
                </div>
            );
        }
    }
    

    If EmployeeLogin component is rendered I want to hide header navigation <HeaderNavContainer /> if not I want to show <HeaderNavContainer />