Directing to a new route on the basis of response from server in React

Viewed 53

I am working in a user authentication project using react-express server . I created a server which sends a confirmation code to the user for creating a new account.However that's not the case if the user enters an email which is already used .So I need to redirect to a new route on the basis of the response of from the server.How should I go from here ownward.

import axios from 'axios';
import React, { Component } from 'react'
import'./reset.css'


export default class reset extends Component {
 constructor(){
 super();
 this.state={
 Email:'',
 Response:''
}
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick(e){
this.setState({
  [e.target.name]:e.target.value
 })
}
handleSubmit(e){
e.preventDefault();
axios.post('http://localhost:5000/resetPassword',{
  Email:this.state.Email
}).then((res)=>{
  if(res.data ==`An email has been sent to ${this.state.Email}`){
   <redirect to ='/home'/>
  }
  else{
  this.setState({
    Email:'',
    Response:res.data
  })
  }
})

}

 render() {
  return (
   <div>
    <div className="Container">
      <div className="subContainer">
        <div className="message">{this.state.Response}</div>
        <p className="notice">Enter your email to reset the password</p>
       <form className="form">
       <input className="takeEmail" type = "email" name="Email" onChange={this.handleClick} value={this.state.Email}placeholder="Enter your email" required/>
       <button type="button" onClick={this.handleSubmit}>Submit</button>
       </form>
      </div>
     </div>      
  </div>
  )
 }
}

I just want to redirect to a new route where a user can enter the confirmation code . I simply want a automatic redirection if certain response is obtained.

1 Answers

If I understood your question correctly. to redirect using react-router in javascript parts of code, you should use history object that is in the route component's props (if your component is not connected to Router directly, you can use withRouter HOC) instead of using <Redirect /> component (it is JSX and only related to render part).

like: this.props.history.push('/route_name', { Email, Response })

you are also checking email message using double equals. you should change it to === (triple equals). also, try to find a better approach to finding out if the request was successful or not.

Related