UNPKG

react-formal

Version:

Classy HTML form management for React

38 lines 1.13 kB
import { useCallback } from 'react'; import { useBindingContext } from './BindingContext'; function extractTargetValue(eventOrValue) { if (!eventOrValue || typeof eventOrValue !== 'object' || !('target' in eventOrValue)) return eventOrValue; const { type, value, checked, multiple, files } = eventOrValue.target; if (type === 'file') return multiple ? files : files && files[0]; if (/number|range/.test(type)) { let parsed = parseFloat(value); return isNaN(parsed) ? null : parsed; } return /checkbox|radio/.test(type) ? checked : value; } function useBinding(bindTo, mapValue = extractTargetValue) { const { updateBindingValue, getValue } = useBindingContext(); const value = getValue(bindTo); const handleEvent = useCallback((...args) => { let mapper = mapValue; if (typeof bindTo === 'string' && typeof mapValue !== 'object') { mapper = { [bindTo]: mapValue }; } if (mapper) { updateBindingValue(mapper, args); } }, [bindTo, mapValue, updateBindingValue]); return [value, handleEvent]; } export default useBinding;