How to hide navbar in login or signup page reactn router

扶醉桌前 提交于 2019-12-08 11:44:24

问题


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 });

  }


来源:https://stackoverflow.com/questions/46342711/how-to-hide-navbar-in-login-or-signup-page-reactn-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!