react-formal
Version:
Classy HTML form management for React
50 lines • 2.17 kB
JavaScript
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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 from 'react';
import Form from './Form';
import useField from './useField';
import { prefix, unprefix } from './Errors';
const propTypes = {
name: PropTypes.string.isRequired,
schema: PropTypes.object,
errors: PropTypes.object,
context: PropTypes.object,
meta: PropTypes.shape({
errors: PropTypes.object.isRequired,
onError: PropTypes.func.isRequired
})
};
/**
* A `Form` component that takes a `name` prop. Functions exactly like a normal
* Form, except that when a `name` is present it will defer errors up to the parent `<Form>`,
* functioning like a `<Form.Field>`.
*
* This is useful for encapsulating complex input groups into self-contained
* forms without having to worry about `"very.long[1].paths[4].to.fields"` for names.
*/
function NestedForm(_ref) {
let {
name,
schema,
errors
} = _ref,
props = _objectWithoutPropertiesLoose(_ref, ["name", "schema", "errors"]);
const [_, meta] = useField({
name,
noValidate: true,
validateOn: null
});
return /*#__PURE__*/React.createElement(Form, _extends({
as: "div"
}, props, {
value: meta.value,
onChange: meta.onChange,
onError: nextErrors => meta.onError(prefix(nextErrors, name)),
errors: unprefix(name ? meta.errors : errors, name),
schema: schema || meta.schema,
context: name ? Object.assign({}, meta.context, props.context) : props.context
}));
}
NestedForm.propTypes = propTypes;
export default NestedForm;