Last active
October 28, 2015 09:29
-
-
Save aakashns/f32c851f227b9d977931 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import React from 'react'; | |
| var Name = React.createClass({ | |
| getInitialState: function() { | |
| return { value: "", errors: [], sync: true }; | |
| }, | |
| validate: function(value) { | |
| var validations = [ | |
| v => v.length < 15 || "Your name is too long!", | |
| v => v.indexOf('@') == -1 || "Your name contains '@'? Really?" | |
| ]; | |
| return validations.map(f => f(value)).filter(e => e !== true); | |
| }, | |
| syncToServer: function() { | |
| clearTimeout(this._syncRequest); | |
| this._syncRequest = setTimeout(() => { | |
| var newState = this.state; | |
| newState.sync = true; | |
| this.setState(newState); | |
| }, 2000); | |
| }, | |
| onValueChange: function(value) { | |
| this.setState({ | |
| value: value, | |
| errors: this.validate(value), | |
| sync: false | |
| }); | |
| this.syncToServer(); | |
| }, | |
| render: function() { | |
| var { value, errors, sync } = this.state | |
| var errorNodes = errors.map((err, i) => <div key={i}>{err}</div>); | |
| var syncNode = value && <div>{ sync ? "Synced!" : "Syncing..." }</div>; | |
| return (<div> | |
| <label>Name : </label> | |
| <input type="text" | |
| value={value} | |
| onChange={e => this.onValueChange(e.target.value)} /> | |
| {errorNodes} | |
| {syncNode} | |
| </div>); | |
| } | |
| }); | |
| export default Name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment