How to Redirect to another page in ReactJS when a IF condition is executed?

11,347
// Are You using BrowserRouter means you can use like this

import PropTypes from 'prop-types';

var users={
    name:'bddebashis',
    password:'debashis111249'
    }

    class Home extends Component {


    constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    static contextTypes = {
        router: PropTypes.object,
      }

     handleSubmit(event) {
        event.preventDefault();
        const data = new FormData(event.target);

        fetch('/api/form-submit-url', {
            method: 'POST',
            body: data,
        });

        if(data.get('usr')==users.name && data.get('paswd')==users.password){
          this.context.router.history.push("/Dashboard")  
        }
      }
    }
Share:
11,347

Related videos on Youtube

Bashis
Author by

Bashis

Updated on June 04, 2022

Comments

  • Bashis
    Bashis almost 2 years

    I want to redirect to Dashboard.jsx if the username and password matches. How to do that ? I am new to ReactJS.

    in the If condition I want to add the redirect code to redirect another page. Pls response. In stackoverflow maximum are using without if condition so here is the difference.

    var users={
    name:'bddebashis',
    password:'debashis111249'
    }
    
    class Home extends Component {
    
    
    constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    
    
     handleSubmit(event) {
        event.preventDefault();
        const data = new FormData(event.target);
    
        fetch('/api/form-submit-url', {
            method: 'POST',
            body: data,
        });
    
        if(data.get('usr')==users.name && data.get('paswd')==users.password){
          <Redirect to='./Dashboard';/>
    
        }
      }
    
  • KCN
    KCN over 5 years
    Thank you so much prabhu, you saved my time.