Skip to content Skip to sidebar Skip to footer

How To Redirect To Another Page Using History On React Js?

I developed a Singnup page using Reactjs on the front-end and laravel on the backend and I want when I click on the button register, it will be redirected to my login page. My Sign

Solution 1:

try to isolate the property before the axios call:

let { history } = this.propsaxios({
    method: 'post',
    url: 'http://172.16.234.24:8000/api/register',
    data: users,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
    })
    .then(function (response) {
      console.log(response);
      history.push('/login');
    })
    .catch(function (response) {
        console.log(response);
    });

Solution 2:

You should wrap the signup component with withRouter higher order component to gain access to this.props.history.

More info in react-router docs

Solution 3:

Just tested this- it redirects just fine.

(within Signup component)..

importReact, { Component } from"react";
const axios = require('axios');

exportdefaultclassSignupextendsComponent {

  constructor(props) {
    super(props); 

    this.state = {}
  }

  handleSubmit = event => {
      event.preventDefault();

        axios({
          method: 'get',
          headers: {
            "Content-type": "application/json"
          },
          url: 'https://jsonplaceholder.typicode.com/todos/1'
          }).then(response => {
            console.log(response); 
            this.props.history.push('/login');
          })
          .catch(response => {
              console.log(response);
          });
    }
  render() {
    return(
       <formonSubmit={this.handleSubmit}><buttontype="submit">
          yo
        </button></form>
     )
  }
}

Try it with the above placeholder code to prove that the redirect works without fail, then replace with your custom API + POST. Note: you may need to stringify the POST payload.

We don't know what your App.js looks like, but your App.js would also need to include the <Router /> component.

Post a Comment for "How To Redirect To Another Page Using History On React Js?"