Advertisement
Guest User

Untitled

a guest
Aug 25th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import React, { Component, PropTypes } from 'react'
  2. import isEqual from 'lodash/isEqual'
  3. import get from 'lodash/get'
  4. import cloneDeep from 'lodash/cloneDeep'
  5. import set from 'lodash/set'
  6.  
  7. export default class Form extends Component {
  8. static propTypes = {
  9. initialValues: PropTypes.object,
  10. validations: PropTypes.object
  11. }
  12.  
  13. static defaultProps = {
  14. initialValues: {}
  15. }
  16.  
  17. constructor(props) {
  18. super(props)
  19. this.state = { values: props.initialValues }
  20. }
  21.  
  22. isPristine = () => {
  23. return isEqual(this.state.values, this.props.initialValues)
  24. }
  25.  
  26. getValue = path => {
  27. return get(this.state.values, path, '')
  28. }
  29.  
  30. setValue = (path, value) => {
  31. this.setState({ values: set(cloneDeep(this.state.values), path, value) })
  32. }
  33.  
  34. getErrors = () => {
  35. if (!this.props.validations) {
  36. return null
  37. }
  38. const errors = Object.keys(this.props.validations).reduce((result, path) => ({
  39. ...result,
  40. [path]: this.props.validations[path]
  41. .map(validation => validation(this.getValue(path), this.state.values))
  42. .find(error => error)
  43. }), {})
  44. return Object.keys(errors).find(path => errors[path]) ? errors : null
  45. }
  46.  
  47. getError = path => {
  48. const errors = this.getErrors()
  49. return errors ? errors[path] : null
  50. }
  51.  
  52. reset = () => {
  53. this.setState({ values: this.props.initialValues })
  54. }
  55.  
  56. render() {
  57. const { initialValues, validations, ...other } = this.props
  58. return (
  59. <form {...other}>
  60. {this.props.children({
  61. ...this.state,
  62. isPristine: this.isPristine,
  63. getValue: this.getValue,
  64. setValue: this.setValue,
  65. getErrors: this.getErrors,
  66. getError: this.getError,
  67. reset: this.reset
  68. })}
  69. </form>
  70. )
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement