Search code examples
reactjsauthenticationcomponentsbrowser-history

browserHistory not Moving to New Component in React


I have this strange authentication issue with react.

When a user logins, the authentication prop is set to true. If a user tries to go into a route and authentication is undefined or false then I push them back to the login page.

Currently it looks like this:

PersonId Component

  componentWillMount() {
    console.log("MOUNTING PERSON ID COMPONENT IF AUTHENTICATED IS TRUE", this.props.authenticated)
    if (!this.props.authenticated) {
        browserHistory.push("/login");     
      }
    }


 render() {    
    if(this.props.user.type == "Admin") 

The problem is, even when this.props.authenticated = undefined, and even when the browser history pushes the component to the login route, the render method for the PersonId component still plays.

This does not make sense. If I push a component to another route why is it still rendering the PersonId component?


Solution

  • The way you are using should work, you can do one more thing, put the same check inside render also, and return null, it will not render anything, like this:

    render() { 
          if (!this.props.authenticated) {
              return null;
          }
          ....
    }