Skip to content

Instantly share code, notes, and snippets.

@geetotes
Last active May 15, 2017 22:37
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 geetotes/50bdbc52b97204c5101ffe8f4337de01 to your computer and use it in GitHub Desktop.
Save geetotes/50bdbc52b97204c5101ffe8f4337de01 to your computer and use it in GitHub Desktop.
class SignUpForm extends React.Component {
constructor(props) {
super(props);
this.state = {
email: null,
username: null,
errorMessages: { // This is new -- if we don't set these defaults, render() will thrown an error
email: [],
username: []
}
};
this._change = this._change.bind(this);
this._validate = this._validate.bind(this);
}
_change(e) {
this.setState({
[e.target.name]: e.target.value
});
}
_validate() {
let valid = true;
let { username, email } = this.state;
let errorMessages = {
username: [],
email: []
};
if (username === null || username === '') {
valid = false;
errorMessages['username'].push('Username is required');
}
if (email === null || email === '') {
valid = false;
errorMessages['email'].push('Email is required');
}
this.setState({
errorMessages: errorMessages
});
if (valid) {
// Don't forget to POST this form or something!
}
}
render() {
return(
<form>
(*) Usernane: <input type='text' name='username' value={this.state.username} onChange={this._change} />
<div className='error'>{this.state.errorMessages.username.join('. ')}</div>
(*) Email: <input type='email' name='email' value={this.state.email} onChange={this._change} />
<div className='error'>{this.state.errorMessages.email.join('. ')}</div>
<button onClick={this._validate}>Submit</button>
</form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment