Skip to content

Instantly share code, notes, and snippets.

@hieuhani
Created September 18, 2018 10:37
Show Gist options
  • Save hieuhani/bf3d35420963a31cf0d851129fe767b7 to your computer and use it in GitHub Desktop.
Save hieuhani/bf3d35420963a31cf0d851129fe767b7 to your computer and use it in GitHub Desktop.
import React from 'react'
import Validator from 'validatorjs'
import styled from 'styled-components'
import en from 'validatorjs/src/lang/en'
import { TextField } from 'office-ui-fabric-react/lib/TextField'
import { DefaultButton } from 'office-ui-fabric-react/lib/Button'
Validator.setMessages('en', en)
const Spacer = styled.div`
height: 20px;
`
const INPUT_PROPS = [
'type',
'disabled',
]
const extractProps = (field) => {
const props = {}
INPUT_PROPS.forEach((prop) => {
if (~INPUT_PROPS.indexOf(prop) && field[prop]) {
props[prop] = field[prop]
}
})
return props
}
export default class BaseForm extends React.Component {
constructor(props) {
super(props)
const initialFormValues = {}
this.rules = {}
props.fields.forEach((field) => {
initialFormValues[field.name] = props.initialValues[field.name] || ''
if (field.rule) {
this.rules[field.name] = field.rule
}
})
this.state = {
values: initialFormValues,
invalid: (() => {
const validation = new Validator(initialFormValues, this.rules)
return validation.fails()
})(),
}
this.validate = () => {
const validation = new Validator(this.state.values, this.rules)
if (this.state.invalid !== validation.fails()) {
this.setState({
invalid: validation.fails(),
})
}
}
this.handleFieldChanged = (fieldName, value) => {
this.setState({
values: {
...this.state.values,
[fieldName]: value,
},
}, () => {
this.validate()
})
}
this.handleSubmit = (e) => {
if (e) {
e.preventDefault()
}
this.props.onSubmit(this.state.values)
}
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<React.Fragment>
{this.props.fields.filter(field => field.type !== 'hidden').map((field) => (
<TextField
key={field.name}
label={field.label}
value={String(this.state.values[field.name])}
onBeforeChange={value => this.handleFieldChanged(field.name, value)}
{...extractProps(field)}
/>
))}
</React.Fragment>
<Spacer />
<DefaultButton
text={this.props.submitAction}
onClick={this.handleSubmit}
type="submit"
disabled={this.state.invalid || this.props.submitting}
/>
</form>
)
}
}
BaseForm.defaultProps = {
initialValues: {},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment