-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseForm.js
More file actions
49 lines (47 loc) · 1.34 KB
/
useForm.js
File metadata and controls
49 lines (47 loc) · 1.34 KB
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
/* Usage:
*
* const [values, { radio, checkbox, tel }] = useForm({accept: "y", phone: "123"});
*
* return (
* <form>
* <input {...radio('accept', 'y')} />
* <input {...radio('accept', 'n')} />
* <input {...checkbox('accepta')} />
* <input {...tel('phone')} />
* </form>
* );
*/
export default function useForm(value) {
const [values, setValues] = useState(value);
const [touched, setTouchedState] = useState({});
const [validity, setValidityState] = useState({});
const generate = type => (name, ownValue) => {
const isCheck = type === "checkbox";
const isRadio = type === "radio";
return {
name,
type,
get checked() {
return isRadio ? ownValue == values[name] : values[name];
},
get value() {
return isRadio ? ownValue : values[name];
},
onChange({ target: { value, checked } }) {
console.log(value, checked)
setValues({ ...values, [name]: isCheck ? checked : value });
},
onBlur(e) {
setTouchedState({ ...touched, [name]: true });
setValidityState({ ...validity, [name]: e.target.validity.valid });
}
};
};
const factory = {
input: generate("input"),
tel: generate("tel"),
checkbox: generate("checkbox"),
radio: generate("radio")
};
return [{ values, validity, touched }, factory];
}