Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import {
- clearErrorOnChange,
- validateAndUpdateErrorsOnBlur
- } from '../../shared/formFunctions';
- /**
- * @param fields (array) fields = ['username', 'password']
- * @param validation (object) validation = { username: { minLength: 10 } }
- * @returns {{ childComponent }}
- * @constructor
- */
- const MakeForm = (fields = [], validation = {}) => (ChildComponent) => {
- if (fields.length === 0) {
- throw new Error('Must supply fields to FormHOC');
- }
- if (typeof validation !== 'object') {
- throw new Error('Validation must be an object');
- }
- return class extends Component {
- constructor(props) {
- super(props);
- this.validation = validation;
- this.state = {
- fields: fields.reduce((prev, curr) => {
- prev[curr] = '';
- return prev;
- }, {}),
- errors: {}
- };
- }
- onChange(event) {
- const { name, value } = event.target;
- const fields = Object.assign({}, this.state.fields, { [name]: value });
- const errors = clearErrorOnChange(event, this.state.errors);
- this.setState({ fields, errors });
- }
- onBlur(event) {
- const errors = validateAndUpdateErrorsOnBlur(
- event,
- this.validation,
- this.state.errors
- );
- if (errors) {
- this.setState({ errors});
- }
- }
- getFields() {
- return Object.assign({}, this.state.fields);
- }
- setFields(newFields) {
- const fields = Object.assign({}, this.state.fields, newFields);
- this.setState({ fields });
- }
- render() {
- return (
- <ChildComponent
- onChange={this.onChange.bind(this)}
- onBlur={this.onBlur.bind(this)}
- getFields={this.getFields.bind(this)}
- setFields={this.setFields.bind(this)}
- {...this.state}
- {...this.props}
- />
- );
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement