Skip to content

Instantly share code, notes, and snippets.

@cuonggt
Created June 16, 2017 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuonggt/87ac20ec304ed61ff5051d8fe55b0782 to your computer and use it in GitHub Desktop.
Save cuonggt/87ac20ec304ed61ff5051d8fe55b0782 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import axios from 'axios';
import FormErrors from './FormErrors';
export default class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
remember: false,
errors: [],
busy: false,
forgotPasswordUrl: '/password/reset'
};
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
this.setState({
errors: [],
busy: true
});
axios.post('/login', { email: this.state.email, password: this.state.password })
.then(response => {
this.setState({
busy: false
});
})
.catch(error => {
let errors;
if (typeof error.response.data === 'object') {
errors = _.flatten(_.toArray(error.response.data));
} else {
errors = ['Something went wrong. Please try again.'];
}
this.setState({
errors: errors,
busy: false
});
});
}
render() {
const { state } = this;
return (
<form className="form-horizontal" role="form" onSubmit={this.onSubmit}>
{state.errors.length > 0 &&
<FormErrors errors={ state.errors } />
}
<div className="form-group">
<label className="col-md-4 control-label">E-Mail Address</label>
<div className="col-md-6">
<input type="email" className="form-control" value={ state.email } onChange={ e => this.setState({ email: e.target.value }) } required />
</div>
</div>
<div className="form-group">
<label className="col-md-4 control-label">Password</label>
<div className="col-md-6">
<input type="password" className="form-control" value={ state.password } onChange={ e => this.setState({ password: e.target.value }) } required />
</div>
</div>
<div className="form-group">
<div className="col-md-6 col-md-offset-4">
<div className="checkbox">
<label>
<input type="checkbox" value={ state.remember } onChange={ e => this.setState({ remember: e.target.checked }) } /> Remember Me
</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-md-8 col-md-offset-4">
<button type="submit" className="btn btn-primary" disabled={ state.busy }>
Login
</button>
<a className="btn btn-link" href={ state.forgotPasswordUrl }>
Forgot Your Password?
</a>
</div>
</div>
</form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment