简体   繁体   中英

how to redirect to homepage after successful login in ReactJS?

how to redirect to homepage after successful login in ReactJS? and also i want to show error message whenever user enter wrong credential.
i am probably new to ReactJS, it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance and also would be much appreciated.

./src/Login.js

import React, {Component} from "react";
import {Form} from 'antd';


export default class App  extends Component{


  constructor(props) {
        super(props);
        this.state ={
            username: "",
            password: "",
        }
        this.onFormSubmit = this.onFormSubmit.bind(this)
    }

    onFormSubmit(values){
      console.log(values);

      const formData = new FormData();
      formData.append("username", values.username);
      formData.append("password", values.password);

        const options = {
            method: 'POST',
            body: formData
        };

      try{
        fetch('http://localhost:8000/api/login', options).then(() => {
          this.props.history.push('/home')
        });
      }

      catch (error) {
        alert('Login Failed. Try Again')
      }

    };


 render(){
    return(

      <div>
                            <Form onFinish={this.onFormSubmit}>
                                <div class="col-md-12 form-group p_star">
                                    <Form.Item name="username">
                                      <input type="text" class="form-control" placeholder="Username"/>
                                    </Form.Item>
                                </div>
                                <div class="col-md-12 form-group p_star">
                                  <Form.Item name="password">
                                    <input type="password" class="form-control"
                                        placeholder="Password"/>
                                   </Form.Item>
                                </div>
                                <div class="col-md-12 form-group">
                                    <button type="submit" value="submit" class="btn_3">
                                        log in
                                    </button>
                                </div>
                            </Form>

     </div>

If you are using react-router then you should use like this

    console.log(values);

    const formData = new FormData();
    formData.append("username", values.username);
    formData.append("password", values.password);

      const options = {
          method: 'POST',
          body: formData
      };

      fetch('http://localhost:8000/api/login', options).then((response) => {

        notification.success({
            message: "login successfully."
        });
        this.props.history.push('/your-homepage-route') <---- Navigate after successful login
      }).catch(error => {
        alert('Login Failed. Try Again') <----- Error Handling
      });
  };```

To redirect to a new page, this is not dependent on react:

window.location = 'http://www.whateveryourpathis.com';

I think for redirection, it will be easy if you are using react-router-dom package for routing:

  1. If you are using it for routing like <Route path="/login" component={Login}/> , this supercharge this component which makes it easy to do programmatic redirects with:

     this.props.history.push('/home')
  2. Otherwise you need to use Height order component from the same package import { withRouter} from 'react-router-dom' then wrap your component with withRouter(Login) finally use this.props.history.push('/home') for redirection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM