UNPKG

react-minimalistic-use-form

Version:

Minimalistic react hook for handling forms without much pain.

62 lines 3.16 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React from 'react'; import { eventHandlers } from './enums'; import { noop } from '../utils/noop'; export var Form = function (_a) { var _b = _a.children, children = _b === void 0 ? [] : _b, bindUseForm = _a.bindUseForm, props = __rest(_a, ["children", "bindUseForm"]); if (bindUseForm === undefined) { throw new Error('Form is missing bindUseForm prop.'); } var _getEventHandler = function (_a) { var _b = _a.callback, callback = _b === void 0 ? noop : _b, _c = _a.handler, handler = _c === void 0 ? eventHandlers.onChange : _c; return function (event) { bindUseForm[handler](event); callback(event); }; }; var addEventHandlersRecursively = function (sourceElements) { return React.Children.map(sourceElements, function (child) { // If it's invalid react element element doesn't have props so no need to clone it if (React.isValidElement(child) === false) { return child; } var _a = child.props, childChildren = _a.children, childOnChange = _a.onChange, childOnBlur = _a.onBlur, childValue = _a.value, childProps = __rest(_a, ["children", "onChange", "onBlur", "value"]); var isInputField = 'name' in childProps && 'id' in childProps; var cloneElementInputProps = {}; if (isInputField) { cloneElementInputProps = { onChange: _getEventHandler({ callback: childOnChange }), onBlur: _getEventHandler({ callback: childOnBlur, handler: eventHandlers.onBlur }), value: childValue, }; if (cloneElementInputProps.value === undefined) { cloneElementInputProps.value = bindUseForm.values[childProps.name] === undefined ? '' : bindUseForm.values[childProps.name]; } } var cloneElementProps = __assign(__assign({}, childProps), cloneElementInputProps); return React.cloneElement(child, cloneElementProps, childChildren === undefined ? undefined : addEventHandlersRecursively(childChildren)); }); }; var formElements = addEventHandlersRecursively(children); return React.createElement("form", __assign({}, props, { ref: bindUseForm.formRef }), formElements); }; //# sourceMappingURL=Form.js.map