Created
November 12, 2015 15:18
-
-
Save ustun/0580a3d0f376a94a01b3 to your computer and use it in GitHub Desktop.
react form example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Utils = require('Utils'); | |
var TestForm = React.createClass({ | |
onSubmit(e) { | |
e.preventDefault(); | |
this.setState({submitAttempted: true}); | |
if (!this.state.inProgress) { | |
this.setState({inProgress: true}); | |
if (this.validate()) { | |
console.log("making the ajax call", this.state.email, this.state.name); | |
} | |
} | |
}, | |
getInitialState() { | |
return {email: '', name: ''}; | |
}, | |
validateEmail() { | |
return Utils.validateEmail(this.state.email); | |
}, | |
validateName() { | |
return this.state.name.length > 3; | |
}, | |
validate() { | |
var isValid = this.validateEmail() && this.validateName(); | |
return isValid; | |
}, | |
setField(fieldName, e) { | |
var x = {}; | |
x[fieldName] = e.target.value; | |
this.setState(x); | |
}, | |
setFieldDirty(fieldName) { | |
var x = {}; | |
x[fieldName + 'Dirty'] = true; | |
this.setState(x); | |
}, | |
render() { | |
var errorNode; | |
if (this.state.submitAttempted && !this.validate()) { | |
errorNode = <div>Your form has errors, please fix</div>; | |
} | |
var errorNodeForEmail; | |
if ((this.state.submitAttempted || this.state.emailDirty) && !this.validateEmail()) { | |
errorNodeForEmail = <div>Please enter a valid email</div>; | |
} | |
return <div className=""> | |
this is the dima form | |
<form onSubmit={this.onSubmit} className="pure-form pure-form-stacked"> | |
<input value={this.state.email} placeholder="email" onChange={_.partial(this.setField, 'email')} onBlur={_.partial(this.setFieldDirty, 'email')}/> | |
{errorNodeForEmail} | |
<input value={this.state.name} placeholder="name" onChange={_.partial(this.setField, 'name')} onBlur={_.partial(this.setFieldDirty, 'name')}/> | |
<button onClick={this.onSubmit} className="pure-button pure-button-primary">Submit</button> | |
</form> | |
{errorNode} | |
</div>; | |
} | |
}); | |
module.exports = TestForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment