How to hide navbar in login or signup page reactn

2019-08-20 12:04发布

问题:

I am using react-router v4 I am creating SPA using that so my navigation menu comes in all page but I don't want it to appear in my login or sign up page. is there anyway to do it?I used localStorage but due to that it remains hidden always

below in my route

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter basename="/sephoraweb">
      <div>
        <HeaderContainer />


        <Route exact path="/" component={LoginContainer} hideNavBar={true} />
        <Route path="/signUp" component={SignUpContainer} />

      </div>
    </BrowserRouter>
 </Provider>,
  document.getElementById('root')
);

and below is my navbar code

 render() {
    if (!this.props.programList) {
      return <Spinner name="circle" />;
    }
    if(!localStorage.getItem("token") || localStorage.getItem("token") == undefined)
       return null;
    const programValues = this.props.programList;

    return <NavBar programs={programValues} />;
  }
}

回答1:

In your MainLayout component's constructor do this.

constructor () {
  this.state = {
    isNavbarHidden: false
  };
}

In your componentDidMount for that component where you want to hide something

componentDidMount () {
  const currentRoute = this.props.location;
  if (currentRoute === 'YOUR_ROUTE_NAME') {
    this.setState({ isNavbarHidden: true });
  }
} // end of componentDidMount

this.props.location is a method of react router which tells you the current path on which the user is at the moment.

Now in your render() method do something like this

render () {
    const { isNavbarHidden } = this.state;
    return (
       <div>
          {!isNavbarHidden && <NavbarComponent />}
          { /* Your rest of the code here *//}
          {this.props.children}
       </div>
    );
}

I hope this helps. Cheers :)



回答2:

With help @Adeel's help I was ble to figure out the solution in my header container I added below code and it worked

 constructor(props) {
    super(props);
    this.state = {
      visibility: true
    };
  }

  componentDidMount() {
         let currentRoutes = this.props.location;


if (currentRoutes.pathname === '/' || currentRoutes.pathname === '/signUp') {

    this.setState({ visibility: false });
  }

    this.props.dispatch(fetchProgramsData());
    this.props.dispatch(fetchCompany());
  }
  componentWillReceiveProps(nextProps){
 let currentRoutes = nextProps.location;
   if (currentRoutes.pathname === '/' || currentRoutes.pathname === '/signUp') {

    this.setState({ visibility: false });
  }
  else
        this.setState({ visibility: true });

  }