redirect when login is successful using react

react router v4 redirect after login
react-redux redirect after login
react redirect to url
react router login example
react redirect to login if not authenticated
react-router redirect after form submit
login/logout in react js
react redirect onclick

I need to make a redirection to another page (component) when user validates successfully with email/password, otherwise, show a warning message on a div that says email or password not correct.

This is my code:

 constructor (props) {
        super(props);
        this.state = {
            // name: "",
          cnx_mail: '',
          cnx_pwd: '',
          joinByEmail: '',
          items: [],
          token : '',
          redirectToReferrer:false,
          errors: {},

          formErrors: {cnx_mail: '', cnx_pwd: ''},
          emailValid: false,
          passwordValid: false,
          formValid: false
        }
         this.handleUserInput = this.handleUserInput.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

     handleSubmit = (event) => {
            event.preventDefault();
            fetch(`${API}/api/connexion`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',   
                  },
                body: JSON.stringify ({
                    email: this.state.cnx_mail,
                    password: this.state.cnx_pwd,
                  })
            })
            .then(res => res.json())
            .then(json => {
                console.log(json);
                localStorage.setItem('toktok', json.result);
                console.log(json[0].role);
//i have to verify email/password bedore redirection
                window.location.href="/accounts";
            }); 
          }

And this is my form in render():

<form className="demoForm" onSubmit={this.handleSubmit} noValidate  encType="application/x-www-form-urlencoded">
                                <div className="alreadysubscribed-input">
                                    <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_mail)}`}>
                                        <input type="email" required className="form-control fatb-input input-form" name="cnx_mail"
                                            value={this.state.cnx_mail}
                                            id="cnx_mail"
                                            onChange={this.handleUserInput} error={errors.cnx_mail} />
                                            <label className="fatb-label" htmlFor="cnx_mail">Email</label>
                                            <div className="fatb-bar"></div>                                  
                                    </div>

                                    <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_pwd)}`}>
                                        <input type="password" required className="form-control fatb-input input-form" name="cnx_pwd"
                                            value={this.state.cnx_pwd}
                                            id="cnx_pwd"
                                            onChange={this.handleUserInput} error={errors.cnx_pwd} />
                                            <label className="fatb-label" htmlFor="cnx_pwd">Mot de passe</label>
                                            <div className="fatb-bar"></div>
                                    </div>
                                </div>
                                <FormErrors formErrors={this.state.formErrors} />

                                <div className="btn-cnx">
                                    {/* <span className="mas">Se connecter</span> */}
                                    <button className="fatb-btn bubbly-button btn-anim3 w100p" type="submit"  name="cnx_btn" disabled={!this.state.formValid}>se connecter</button>
                                </div>
                            </form>

i need to verify if the role == "admin" then redirect to /accounts, otherwise display a warning msg in a div for example.

this is the structure of my data :

{
    "success": true,
    "message": "SUCCESS",
    "result": [
        {
            "dateCreation": "2019-10-09T21:54:18.491Z",
            "resetpasswordtoken": null,
            "resetpasswordexpires": null,
            "role": "admin",
            "enable": true,
            "_id": "5d9e67772682971c1fc3711c",
            "email": "meachemlal@gmail.com",
            "password": "$2b$10$HqEMSkaWBZ..BFvSpxliUu/02vWodvxYoFZMaYUU5ZsBeqeZB4jLu",
            "tickets": [],
            "gains": [],
            "__v": 0,
            "nom": "ACHEMLAL",
            "prenom": "MERYEM",
            "tel": "+33619562721"
        },
        {
            "dateCreation": "2019-10-09T21:54:18.491Z",
            "resetpasswordtoken": null,
            "resetpasswordexpires": null,
            "role": "admin",
            "enable": true,
            "_id": "5d9e677e2682971c1fc3711d",
            "email": "mika.achemlal@gmail.com",
            "password": "$2b$10$Bg4nOrNMzc.b/JBNKNiRP.BiMd/.h4CHKiy0nvV/uim0d3VwHl9iq",
            "tickets": [],
            "gains": [],
            "__v": 0
        },
    ........

For redirect page, you can write code window.location.href, as I describe below.

componentDidMount() {
    const token =  localStorage.getItem('toktok');
    fetch(`${API}/api/accounts`,{
        headers :{
            'authorization': `Bearer ${token}`, 
        }
    })
    .then(results => {
        return results.json();
    })
    .then(data => {
        this.setState({ items: data.result });
        window.location.href="/nextpageurl";
    })
    .catch(err => {
        console.log("error : ",err);
    });
 }

And Before redirect page validation:-

  import { AvForm,AvField} from 'availity-reactstrap-validation';
    <AvForm onValidSubmit={this.onSubmit} name="login" className="app_start_form">
      <div className="form-group">
       <span className="icon"><img src={email} alt="" /></span> 
        <AvField type="text" ng-model="user.Email" name="username" value={this.state.username} onChange={this.onChange} className="form-control" placeholder="Email/Mobile No.*" 
                           validate={{
                            pattern: { value: /^((([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))|([0-9]{9,}))\w+$/, errorMessage: 'Please enter valid emailid or mobile no' },
                            required: { value: true, errorMessage: "Email or Mobile No. is required" },
                            maxLength: { value: isMobile, errorMessage: 'Mobile No. must be maximum '+isMobile+' digits' }
                          }} />
 <AvField type="password" name="password" autoFocus value={this.state.password} onChange={this.onChange} className="form-control" placeholder="Password *" 
                           validate={{
                            required: { value: true, errorMessage: "Password is required" },
                            pattern: { value:/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/, errorMessage: 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit' },
                            minLength: { value: 8, errorMessage: 'Password must be at least 8 characters' },
                            maxLength: { value: 20, errorMessage: 'Password not more then 20 characters' }
                          }} /> 
                        </div>

       <div className="sec_btn loginbtn_ind">
         <button type="submit" className="btn blue_btn">SIGN IN</button>
        </div>
     </AvForm>

Authentication with Redirect ― Scotch.io, We can use the Redirect component supplied to us by react-router-dom to direct up so that we are taken to our root route after we have a successful login. Programmatic navigation means redirection occurs on that route when a particular event happens, for example when a user clicks on a login button, if login is successful we need to redirect them to private route. There are two possible ways we can do Programmatic navigation. First way using the Redirect component.

You will have to use a library for your routing needs. Some of the popular ones are react-router, reach-router etc. React philosophically, is not opinionated about which router is used nor does it ship with one.

Assuming: You are using react-router

in .then

.then(data => {
    this.setState({ items: data.result });
    this.props.history.push('/nextpage');        
})

How to Router Redirect After Login, React uses Redux's state for maintaining state throughout the app. we are going to learn how to redirect a user after a successful login. React uses Redux's state for maintaining state throughout the app. The purpose of the state is to keep your application state synchronized with the Redux store. In this guide, we are going to learn how to redirect a user after a successful login.. Usually, when we are building web apps, there's a requirement that the user must be logged in to use the app.

try using history.push

like this: this.props.history.push('/RedirectTargetComponent');

react router - Redirection after login, I would like to redirect to a url depending on the success or failure of user login . I have tried to do the following First created a history using. let  To complete the login flow we are going to need to do two more things. Redirect the user to the homepage after they login. And redirect them back to the login page after they logout. We are going to use the useHistory hook that comes with React Router. Redirect to Home on Login. First, initialize useHistory hook in the beginning of src/containers/Login.js.

React JS + React Router, Today I spent some time figuring out how to redirect a successfully logged on user from the login page to the main application page. The easiest way to accomplish this is using react-router. There are several concepts at play here. A “page” is a route. The route is an association between a url (or a url pattern), like “/login”, and a component.

Create a ProtectedRoute for Logged In Users with Route, Redirect , We'll combine a Route with a render prop and use a loggedIn prop to the location the user visited and redirect them back to the protected route once they login. for Logged In Users with Route, Redirect, and a Render Prop in React Router login, but think of it as a way to help guide the user through the path to success. We can use the Redirect component supplied to us by react-router-dom to direct users away from pages they shouldn't be able to get to. Returning a Redirect component will cause the page to redirect to the page we desire. To demonstrate this, let's add a login form to protect our CMS from unauthenticated users. This will be a very simple login form.

How can I redirect after successful post? [React/Redux/Node , I'm trying to use react-router-dom Redirect to send the user to their dashboard once they submit a form and the POST request succeeds. I can't  Redirect Component If you have routes in your React app, you’re probably using React Router (or React Router DOM) to set up your routes. Considering you’ve already installed the React Router

Comments
  • Which routing library are you using? If you are using react-router you can look here of how to redirect to another page upon successful login. reacttraining.com/react-router/web/example/auth-workflow
  • please mention which library you are using to set routes.
  • Yes, it's react-router
  • sorry it's not really clear for me the link :/ i need to check if the mail/password are good
  • But how can i check if the password and email are correct before redirect please?
  • i updated my post for more details about the issue
  • Hey, can i use that without library ?
  • If you use react-router than yes. Take a look here serverless-stack.com/chapters/redirect-on-login-and-logout.html
  • You will have to use a library for your routing needs. Some of the popular ones are react-router, reach-router etc. React philosophically, is not opinionated about which router is used nor does it ship with one.
  • i updated my post for more details about the issue