forked from equinor/webviz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckbox.tsx
69 lines (59 loc) · 2.22 KB
/
checkbox.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
import React from "react";
import { resolveClassNames } from "@lib/utils/resolveClassNames";
import { v4 } from "uuid";
import { BaseComponent, BaseComponentProps } from "../BaseComponent";
export type CheckboxProps = {
id?: string;
name?: string;
label?: React.ReactNode;
checked?: boolean;
indeterminate?: boolean;
onChange?: (event: React.ChangeEvent<HTMLInputElement>, checked: boolean) => void;
} & BaseComponentProps;
function CheckboxComponent(props: CheckboxProps, ref: React.ForwardedRef<HTMLDivElement>) {
const { onChange } = props;
const [checked, setChecked] = React.useState<boolean>(props.checked ?? false);
const id = React.useRef<string>(props.id ?? `checkbox-${v4()}`);
React.useEffect(() => {
setChecked(props.checked ?? false);
}, [props.checked]);
const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
if (props.checked === undefined) {
setChecked(event.target.checked);
}
onChange && onChange(event, event.target.checked);
},
[setChecked, onChange, props.checked]
);
return (
<BaseComponent ref={ref} disabled={props.disabled} className="flex gap-2 items-center">
<input
id={props.id ?? id.current}
name={props.name}
ref={(el) => el && (el.indeterminate = props.indeterminate ?? false)}
type="checkbox"
checked={checked}
onChange={handleChange}
className={resolveClassNames(
"w-4",
"h-4",
"text-blue-600",
"border-gray-300",
"rounded",
"focus:ring-blue-500",
"cursor-pointer"
)}
/>
{props.label && (
<label
htmlFor={props.id ?? id.current}
className={resolveClassNames("block", "text-gray-900", "cursor-pointer")}
>
{props.label}
</label>
)}
</BaseComponent>
);
}
export const Checkbox = React.forwardRef(CheckboxComponent);