-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseBooleanField.ts
More file actions
44 lines (34 loc) · 978 Bytes
/
useBooleanField.ts
File metadata and controls
44 lines (34 loc) · 978 Bytes
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
import { useContext } from 'react';
import { BooleanFieldI18nContext } from './BooleanFieldI18n';
import { useFieldValidator } from '../../helpers/useFieldValidator';
import { FieldContext } from '../../typings/FieldContext';
import { FieldConfig, useField } from '../Field/useField';
export type BooleanFieldConfig = FieldConfig<boolean | null | undefined> & {
required?: boolean;
};
export type BooleanFieldBag = FieldContext<boolean | null | undefined> & {
onBlur: () => void;
};
export const useBooleanField = ({ required, ...config }: BooleanFieldConfig) => {
const fieldBag = useField(config);
const {
control: { setTouched },
} = fieldBag;
const i18n = useContext(BooleanFieldI18nContext);
const onBlur = () => {
setTouched({ $touched: true });
};
useFieldValidator({
name: config.name,
validator: (value) => {
if (required && !value) {
return i18n.required;
}
return undefined;
},
});
return {
...fieldBag,
onBlur,
};
};