skip to Main Content

I have a web site, and right now whether I’m logged or not, when I go to the root it shows my log in form. What I want is that if I’m logged and got to / redirect to /api/admin

Here is what my route config looks like:

const routes = {
  path: '/',
  component: App;
  indexRoute: { component: Login },
  childRoutes: [
     { path: 'twitter', component: TwitterIn },
  ]
}

My question is how can I put some login here, something like

 if (UserLogged) {
     //goto /api/admin
 } else {
    //behave just like is behaving now
 }

2

Answers


  1. If you are using React-Router, wrap your default exported component using withRouter. You can import it using:

    import { withRouter } from "react-router";
    

    And when you are using the default export, you can do this way:

    const Comp extends React.Component {
      // ...
    }
    export default withRouter(Comp);
    

    The withRouter higher-order component will pass updated match, location, and history props to the wrapped component whenever it renders.

    And in the constructor or wherever you are checking for the condition, you can use this.props.history and redirect this way:

    if (UserLogged) {
      // goto /api/admin
      this.props.history.replace("/api/admin");
    }
    

    If that’s not possible, you can use the <Redirect /> API, which can be imported this way:

    import { Route, Redirect } from 'react-router';
    

    This works only if you are inside the render function (I guess).

    render() {
      if (UserLogged) {
        // goto /api/admin
        return <Redirect to="/api/admin" />;
      }  
      return (
        <p>Your usual HTML</p>
      );
    }
    
    Login or Signup to reply.
  2. In my last project, I defined all the routing within a React Component. Within that Component, ‘user’ was defined as a state property set to either ‘null’ (logged out) or a valid user object (logged in). The Component’s rendering logic then returned one set of routes (redirecting to the login page) if the user was logged out and a different set of routes (full application routes) if the user was logged in.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search