Not redirecting to desired page

How can I get the loginState in Navigation, so after successful login system should redirect to Profile screen. Now after successful login, it is not Redirecting to profile screen. I have read few tutorials but all with complex details, I would like to have some simple way of implementing this, as I have only 4 screens.

I have added a demo below:

https://codesandbox.io/s/amazing-ellis-2h3pd?file=/src/components/Home.js

3 answers

  • answered 2020-06-02 07:16 Rafael Rocha

    Since it's a funcional component it won't re-render and therefore calling the ternary in the return statement again. What I recomment you to do is, in the handleSubmit:

    const Login = (props) => {
      const [email, setEmail] = useState("");
      const [password, setPassword] = useState("");
      const userEmail = "sample@test.com";
      const userPassword = "1234";
    
      const handleSubmit = e => {
        e.preventDefault();
        if (email === userEmail && password === userPassword) {
          alert("Success");
          setLoginState(true);
          props.history.replace('/');
        } else {
          alert("Login details not correct !");
        }
      };
    
      return (
        <div className="login_wrapper">
          <div className="login_player_column_layout_one">
            <div className="login_player_Twocolumn_layout_two">
              <form onSubmit={handleSubmit} className="myForm">
                <div className="formInstructionsDiv formElement">
                  <h2 className="formTitle">Login</h2>
                </div>
                <div className="loginfillContentDiv formElement">
                  <label>
                    <input
                      className="inputRequest formContentElement"
                      type="text"
                      placeholder="Email"
                      onChange={e => setEmail(e.target.value)}
                    />
                  </label>
                  <label>
                    <input
                      className="inputRequest formContentElement"
                      type="password"
                      placeholder="Password"
                      onChange={e => setPassword(e.target.value)}
                    />
                  </label>
                  <label>
                    <span className="loginValidationText" />
                  </label>
                </div>
                <div className="loginsubmitButtonDiv formElement">
                  <button type="submit" className="submitButton">
                    Login
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      );
    };
    

    And then you can avoid using the <Redirect /> component. Hope this helps :)

  • answered 2020-06-02 07:41 Hagai Harari

    To use props.history in a component, you should wrap your component with withRouter


     import { withRouter } from 'react-router-dom'
    
     ....rest code...
    
     export default withRouter(Login)
    

    Another way to achieve your desired behavior is at route declaration itself do


      <Route path="/login" render={()=> loginstate ? < Redirect to= 'profile' /> : <Login/>} />
    

    What more adapt to a real scenario usage, while loginstate isn't live just a Login component but at some root place at your project

  • answered 2020-06-02 09:02 Tejal

    1. On successful sign in, store flag in local storage

      localStorage.setItem('userLoggedIn', true);

    2. App.js : Allow user to access signing in related pages without restriction

    const App = () => {
      return (
        <div className="App">
            <Switch>
              <Route exact path="/signIn" component={SignIn} />
              <Route exact path="/signUp" component={SignUp} />
              <Route exact path="/forgotPassword" component={ForgotPassword} />
              
              <PrivateRoute path="/" component={Dashboard} />
            </Switch>
        </div>
      );
    }

    1. PrivateRoute.js : if user is not logged in always get redirected to sign in

    const PrivateRoute = ({ component: Component, ...rest }) => (
        <Route {...rest} render={props => (
            localStorage.getItem('userLoggedIn')
                ? <Component {...props}></Component>
                : <Redirect to={{ pathname: '/signIn', state: { from: props.location } }} />
        )} />
    );

    1. Dashboard.js : After sign in user can access Dashboard

    class Dashboard extends Component {
        render() {
            return (
                <div>
                  <Header />
                  <div>
                    <Switch>
                      <Route exact path="/" component={MY_PROFILE} />
                      <Route exact path="/myProfile" component={MyProfile} />
                    </Switch>
                  </div>
                </div>
            );
        }
    }