-
Notifications
You must be signed in to change notification settings - Fork 101
/
Form.js
50 lines (43 loc) · 1.25 KB
/
Form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import * as React from 'react'
import Value from './Value'
import renderProps from '../utils/renderProps'
const isObject = value => typeof value === 'object' && value
const Form = ({ initial = {}, onChange, ...props }) => (
<Value initial={{ ...initial }} onChange={onChange}>
{({ value: values, set, reset }) =>
renderProps(props, {
values,
reset,
setValues: nextValues =>
set(prev => ({
...prev,
...(typeof nextValues === 'function'
? nextValues(prev)
: nextValues),
})),
field: id => {
const value = values[id]
const setValue = updater =>
typeof updater === 'function'
? set(prev => ({ ...prev, [id]: updater(prev[id]) }))
: set({ ...values, [id]: updater })
return {
value,
set: setValue,
bind: {
value,
onChange: event => {
if (isObject(event) && isObject(event.target)) {
setValue(event.target.value)
} else {
setValue(event)
}
},
},
}
},
})
}
</Value>
)
export default Form