Created
March 20, 2017 20:11
-
-
Save robrichard/19ffce2d935a3bf1e9c1ae36bf160526 to your computer and use it in GitHub Desktop.
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
class MyForm extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
input: { | |
email: "", | |
name: "" | |
}, | |
blurred: { | |
email: false, | |
name: false | |
} | |
}; | |
} | |
handleInputChange(newPartialInput) { | |
this.setState(state => ({ | |
...state, | |
input: { | |
...state.input, | |
...newPartialInput | |
} | |
})) | |
} | |
handleBlur(fieldName) { | |
this.setState(state => ({ | |
...state, | |
blurred: { | |
...state.blurred, | |
[fieldName]: true | |
} | |
})) | |
} | |
validate() { | |
const errors = {}; | |
const {input} = this.state; | |
if (!input.email) { | |
errors.email = 'Email is required'; | |
} else if (!isEmailValid(input.email)) { | |
errors.email = 'Please enter a valid email'; | |
} | |
if (!input.name) { | |
errors.name = 'Name is required'; | |
} | |
return { | |
errors, | |
isValid: Object.keys(errors).length === 0 | |
}; | |
} | |
render() { | |
const {input, blurred} = this.state; | |
const {errors, isValid} = this.validate(); | |
return ( | |
<form onSubmit={() => /* save your form here */}> | |
<div> | |
<input | |
name="email" | |
placeholder="email" | |
value={input.email} | |
onBlur={() => this.handleBlur('email')} | |
onChange={e => this.handleInputChange({email: e.target.value})} | |
/> | |
{blurred.email && !!errors.email && <span>{errors.email}</span>} | |
</div> | |
<div> | |
<input | |
name="name" | |
placeholder="name" | |
value={input.name} | |
onBlur={() => this.handleBlur('name')} | |
onChange={e => this.handleInputChange({name: e.target.value})} | |
/> | |
{blurred.name && !!errors.name && <span>{errors.name}</span>} | |
</div> | |
<div> | |
<button type="submit" disabled={!isValid}> | |
Submit | |
</button> | |
</div> | |
</form> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment