UNPKG

react-formal

Version:

Classy HTML form management for React

57 lines 2.13 kB
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } import PropTypes from 'prop-types'; import React, { useContext, useMemo } from 'react'; import { FormContext } from './Contexts'; import { filterAndMapErrors } from './Errors'; import uniq from './utils/uniqMessage'; let flatten = (arr, next) => arr.concat(next); /** * Represents a Form validation error message. Only renders when the * value that it is `for` is invalid. * * @alias FormMessage * @memberof Form */ function Message(_ref) { let { errors: propsErrors, for: names, className, filter = uniq, extract = error => error.message || error, children = (errors, msgProps) => /*#__PURE__*/React.createElement("span", msgProps, errors.join(', ')) } = _ref, props = _objectWithoutPropertiesLoose(_ref, ["errors", "for", "className", "filter", "extract", "children"]); const { errors: formErrors } = useContext(FormContext); const inputErrors = propsErrors || formErrors; const errors = useMemo(() => filterAndMapErrors({ errors: inputErrors, names }), [names, inputErrors]); if (!errors || !Object.keys(errors).length) return null; return /*#__PURE__*/React.createElement(React.Fragment, null, children(Object.values(errors).reduce(flatten, []).filter(filter).map(extract), Object.assign({}, props, { className }))); } Message.propTypes = { for: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), /** * A function that maps an array of message strings * and returns a renderable string or ReactElement. * * ```jsx static * <Message> * {errors => errors.join(', ')} * </Message> * ``` */ children: PropTypes.func, /** * Map the passed in message object for the field to a string to display */ extract: PropTypes.func, filter: PropTypes.func }; export default Message;