Last active
November 23, 2017 12:33
-
-
Save souhe/7537de23250cddee07c7c071277460fc 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
import React, { Component } from 'react'; | |
import Input from './Input'; | |
import { validate } from './validation'; | |
class LoginForm extends Component { | |
rules = { | |
name: (value) => !value && 'name cannot be empty' // Some rules for each fields | |
} | |
handleSubmit = () => { | |
const { isValid, errors } = validate(this.rules, this.state.fields); | |
if (isValid) { | |
// TODO: submit data | |
} else { | |
this.setState({ errors }); | |
} | |
} | |
handleFieldChange = (fieldName, value) => { | |
const newFields = { | |
...this.state.fields, | |
[fieldName]: value | |
} | |
const { isValid, errors } = this.props.validate(this.rules[fieldName], newFields); | |
this.setState(state => ({ | |
fields: newFields, | |
errors | |
})); | |
} | |
render { | |
return ( | |
<div> | |
<Input | |
label="name" | |
value={this.state.fields.name} | |
errorMessage={this.state.errors.name} | |
/> | |
<button onClick={this.handleSubmit} /> | |
</div> | |
); | |
} | |
} | |
export default LoginForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment