UNPKG

@shopify/react-form-state

Version:

Manage React forms tersely and type-safely with no magic

80 lines (69 loc) 2.06 kB
import { objectSpread2 as _objectSpread2 } from '../_virtual/_rollupPluginBabelHelpers.js'; import React from 'react'; import { mapObject, replace } from '../utilities.mjs'; class List extends React.PureComponent { constructor(...args) { super(...args); this.changeHandlers = new Map(); this.handleChange = ({ index, key }) => { const hashKey = `${index}:${key}`; if (this.changeHandlers.has(hashKey)) { return this.changeHandlers.get(hashKey); } const handler = newValue => { const { field: { onChange } } = this.props; onChange(value => { const existingItem = value[index]; const newItem = _objectSpread2(_objectSpread2({}, existingItem), {}, { [key]: typeof newValue === 'function' ? newValue(value[index][key]) : newValue }); return replace(value, index, newItem); }); }; this.changeHandlers.set(hashKey, handler); return handler; }; } render() { const { field: { value, initialValue, error, name, onBlur }, getChildKey, children } = this.props; return value.map((fieldValues, index) => { const innerFields = mapObject(fieldValues, (value, fieldPath) => { const initialFieldValue = initialValue && initialValue[index] && initialValue[index][fieldPath]; return { value, onBlur, name: `${name}.${index}.${fieldPath}`, initialValue: initialFieldValue, dirty: value !== initialFieldValue, error: error && error[index] && error[index][fieldPath], onChange: this.handleChange({ index, key: fieldPath }) }; }); const key = getChildKey ? getChildKey(fieldValues) : index; return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, children(innerFields, index)); }); } } export default List;