Skip to content

Instantly share code, notes, and snippets.

@souhe
Last active November 23, 2017 12:33
Show Gist options
  • Save souhe/7537de23250cddee07c7c071277460fc to your computer and use it in GitHub Desktop.
Save souhe/7537de23250cddee07c7c071277460fc to your computer and use it in GitHub Desktop.
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