UNPKG

react-verificator

Version:
51 lines (50 loc) 1.97 kB
import React, { Component } from 'react'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { Validator } from 'verificator/es'; const defaultMapToProps = ({ validator }) => ({ validator }); export default function validator(options, mapToProps = defaultMapToProps) { const validator = new Validator({}, options.rules, options.customLocale); if (typeof mapToProps !== 'function') { mapToProps = defaultMapToProps; } function wrapWithValidatorComponent(WrappedComponent) { const displayName = `Validator(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`; class Validator extends Component { constructor(props) { super(props); this.state = { validator: validator }; } componentWillMount() { this.unsubscribe = this.state.validator.subscribe(() => { this.setState({ validator: this.state.validator, }); }); } componentWillUnmount() { this.unsubscribe(); } calculateMapToProps() { const result = { validator, ownProps: this.props, }; return mapToProps(result); } render() { const { props } = this; const validatorProps = this.calculateMapToProps(); const mergedPropsAndValidator = Object.assign({}, props, validatorProps); return (React.createElement(WrappedComponent, Object.assign({}, mergedPropsAndValidator))); } } Validator.displayName = displayName; Validator.WrappedComponent = WrappedComponent; return hoistNonReactStatics(Validator, WrappedComponent); } return wrapWithValidatorComponent; }