UNPKG

@shopify/react-form-state

Version:

Manage React forms tersely and type-safely with no magic

62 lines (54 loc) 1.48 kB
import { objectSpread2 as _objectSpread2 } from '../_virtual/_rollupPluginBabelHelpers.js'; import React from 'react'; import { mapObject } from '../utilities.mjs'; class Nested extends React.PureComponent { constructor(...args) { super(...args); this.changeHandlers = new Map(); this.handleChange = key => { if (this.changeHandlers.has(key)) { return this.changeHandlers.get(key); } const handler = newValue => { const { field: { onChange } } = this.props; onChange(value => { return _objectSpread2(_objectSpread2({}, value), {}, { [key]: typeof newValue === 'function' ? newValue(value[key]) : newValue }); }); }; this.changeHandlers.set(key, handler); return handler; }; } render() { const { field: { name, value, onBlur, initialValue, error }, children } = this.props; const innerFields = mapObject(value, (value, fieldPath) => { const initialFieldValue = initialValue && initialValue[fieldPath]; return { value, onBlur, name: `${name}.${fieldPath}`, initialValue: initialFieldValue, dirty: value !== initialFieldValue, error: error && error[fieldPath], onChange: this.handleChange(fieldPath) }; }); return children(innerFields); } } export default Nested;