0

I want to translate an angularjs login page to reactjs. I did the code but I want to know if it's the right way to do it and if it's correct till what I have done. Also I want to add the dashboard page which can be accessed only authentication and user will be redirected to dashboard after login.

$scope.login=function(){
    $scope.newuser={
        'password':$scope.signinpassword,
        'email':$scope.emailid
    }
   return $http.post('/api/authenticate',$scope.newuser).then(function(response,status){
        if(response.data=='redirect'){
            $window.location.href="/dashboard";                        
        }else if(response.data=='verifyemail'){
            angular.element(document.querySelector('#verifyemailbtn')).click();                
        }else if(response.data=='Invalid Password'){
            window.alert("Incorrect Password");
            $scope.error='Failed to authenticate'
        }       
   });
}

my reactjs code that I translated so far

class Login extends Component {
constructor(props){
  super(props);
  this.state={
  emailid:'',
  password:''
  }
 }
performLogin = async (event) => {
    var body={
        "emailid":"this.state.emailid",
        "password":"this.state.password"
        }
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: body
    };
    const url = "api/login";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      console.log(`login successful`);
    } catch (error) {
      console.error("login credentials wrong");
    }
  };

render() {
    return (
      <div>
             <input type="text"
             placeholder="emailid"
             onChange = {(event,newValue) => this.setState({emailid:newValue})}
             />
            <br/>
             <input
               type="password"
               placeholder="Enter your Password"
               onChange = {(event,newValue) => this.setState({password:newValue})}
              />
            <br/>
             <button type="submit" onClick={(event) => this.performLogin(event)}/>
      </div>
    );
  }
}
export default Login;   
UbuntuNewb
  • 391
  • 2
  • 10

1 Answers1

1

your code approaching is ok but have some syntax issues.

1- your need to bind "this" for methods in constructor

2- remove double quotation in performLogin for this.state.emailid

3- you don't need many functions for each input you can just handle all input feilds just with one function like so.

i refactor your code :-)

class Login extends Component {
constructor(props){
  super(props);
  
  this.performLogin = this.performLogin.bind(this)
  this.handleChange = this.handleChange.bind(this)
  this.state={
  emailid:'',
  password:''
  }
 }
 
 
performLogin = async (event) => {
    const { enteredText } = this.state;
    var body={
        "emailid":this.state.emailid,
        "password":this.state.password
        }
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: body
    };
    const url = "api/login";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      $window.location.href="/dashboard";
    } catch (error) {
      console.error("login credentials wrong");
    }
  };
  
  
  handleChange(e) {
    this.setState({[e.target.name]:e.target.value})
  }

render() {
    return (
      <div>
             <input type="text"
             placeholder="emailid"
             onChange = {handleChange}
             />
            <br/>
             <input
               type="password"
               placeholder="Enter your Password"
               onChange = {handleChange}
              />
            <br/>
             <button type="submit" onClick={this.performLogin}/>
      </div>
    );
  }
}
export default Login;   

for redirecting you can use lib like React-Router or just replace console.log(login successful) with $window.location.href="/dashboard"

Amir Rezvani
  • 744
  • 6
  • 23
  • thanks. could also show me how to redirect to dashboard(which should be only accessible after authentication) – UbuntuNewb Dec 07 '19 at 07:24
  • dashboard.js could still be accessed without logging in. i want it to be accessible only after login – UbuntuNewb Dec 07 '19 at 14:52
  • for Sure if you follow this link https://reacttraining.com/react-router/web/example/recursive-paths – Amir Rezvani Dec 08 '19 at 12:08
  • and if you also don't want to use react-router save token in localstorage at login - then check if token exist then load dashboard component if not return null – Amir Rezvani Dec 08 '19 at 12:10