forked from rjsf-team/react-jsonschema-form
/
CheckboxWidget.tsx
94 lines (88 loc) · 2.25 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import React, { useCallback } from "react";
import {
getTemplate,
schemaRequiresTrueValue,
FormContextType,
RJSFSchema,
StrictRJSFSchema,
WidgetProps,
} from "@rjsf/utils";
/** The `CheckBoxWidget` is a widget for rendering boolean properties.
* It is typically used to represent a boolean.
*
* @param props - The `WidgetProps` for this component
*/
function CheckboxWidget<
T = any,
S extends StrictRJSFSchema = RJSFSchema,
F extends FormContextType = any
>({
schema,
uiSchema,
options,
id,
value,
disabled,
readonly,
label,
autofocus = false,
onBlur,
onFocus,
onChange,
registry,
}: WidgetProps<T, S, F>) {
const DescriptionFieldTemplate = getTemplate<
"DescriptionFieldTemplate",
T,
S,
F
>("DescriptionFieldTemplate", registry, options);
// 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 handleChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) =>
onChange(event.target.checked),
[onChange]
);
const handleBlur = useCallback(
(event: React.FocusEvent<HTMLInputElement>) =>
onBlur(id, event.target.checked),
[onBlur, id]
);
const handleFocus = useCallback(
(event: React.FocusEvent<HTMLInputElement>) =>
onFocus(id, event.target.checked),
[onFocus, id]
);
return (
<div className={`checkbox ${disabled || readonly ? "disabled" : ""}`}>
{schema.description && (
<DescriptionFieldTemplate
id={id + "__description"}
description={schema.description}
schema={schema}
uiSchema={uiSchema}
registry={registry}
/>
)}
<label>
<input
type="checkbox"
id={id}
name={id}
checked={typeof value === "undefined" ? false : value}
required={required}
disabled={disabled || readonly}
autoFocus={autofocus}
onChange={handleChange}
onBlur={handleBlur}
onFocus={handleFocus}
/>
<span>{label}</span>
</label>
</div>
);
}
export default CheckboxWidget;