forked from rjsf-team/react-jsonschema-form
/
CheckboxWidget.tsx
60 lines (57 loc) · 1.56 KB
/
CheckboxWidget.tsx
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
51
52
53
54
55
56
57
58
59
60
import React from "react";
import { Checkbox, FormControl, Text } from "@chakra-ui/react";
import {
WidgetProps,
schemaRequiresTrueValue,
StrictRJSFSchema,
RJSFSchema,
FormContextType,
} from "@rjsf/utils";
import { getChakra } from "../utils";
export default function CheckboxWidget<
T = any,
S extends StrictRJSFSchema = RJSFSchema,
F extends FormContextType = any
>(props: WidgetProps<T, S, F>) {
const {
id,
value,
disabled,
readonly,
onChange,
onBlur,
onFocus,
label,
uiSchema,
schema,
} = props;
const chakraProps = getChakra({ uiSchema });
// Because an unchecked checkbox will cause html5 validation to fail, only add
// the "required" attribute if the field value must be "true", due to the
// "const" or "enum" keywords
const required = schemaRequiresTrueValue<S>(schema);
const _onChange = ({
target: { checked },
}: React.ChangeEvent<HTMLInputElement>) => onChange(checked);
const _onBlur = ({
target: { value },
}: React.FocusEvent<HTMLInputElement | any>) => onBlur(id, value);
const _onFocus = ({
target: { value },
}: React.FocusEvent<HTMLInputElement | any>) => onFocus(id, value);
return (
<FormControl mb={1} {...chakraProps} isRequired={required}>
<Checkbox
id={id}
name={id}
isChecked={typeof value === "undefined" ? false : value}
isDisabled={disabled || readonly}
onChange={_onChange}
onBlur={_onBlur}
onFocus={_onFocus}
>
{label && <Text>{label}</Text>}
</Checkbox>
</FormControl>
);
}