Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component, PropTypes } from 'react'
- import isEqual from 'lodash/isEqual'
- import get from 'lodash/get'
- import cloneDeep from 'lodash/cloneDeep'
- import set from 'lodash/set'
- export default class Form extends Component {
- static propTypes = {
- initialValues: PropTypes.object,
- validations: PropTypes.object
- }
- static defaultProps = {
- initialValues: {}
- }
- constructor(props) {
- super(props)
- this.state = { values: props.initialValues }
- }
- isPristine = () => {
- return isEqual(this.state.values, this.props.initialValues)
- }
- getValue = path => {
- return get(this.state.values, path, '')
- }
- setValue = (path, value) => {
- this.setState({ values: set(cloneDeep(this.state.values), path, value) })
- }
- getErrors = () => {
- if (!this.props.validations) {
- return null
- }
- const errors = Object.keys(this.props.validations).reduce((result, path) => ({
- ...result,
- [path]: this.props.validations[path]
- .map(validation => validation(this.getValue(path), this.state.values))
- .find(error => error)
- }), {})
- return Object.keys(errors).find(path => errors[path]) ? errors : null
- }
- getError = path => {
- const errors = this.getErrors()
- return errors ? errors[path] : null
- }
- reset = () => {
- this.setState({ values: this.props.initialValues })
- }
- render() {
- const { initialValues, validations, ...other } = this.props
- return (
- <form {...other}>
- {this.props.children({
- ...this.state,
- isPristine: this.isPristine,
- getValue: this.getValue,
- setValue: this.setValue,
- getErrors: this.getErrors,
- getError: this.getError,
- reset: this.reset
- })}
- </form>
- )
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement