-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
74 lines (66 loc) · 1.88 KB
/
App.tsx
File metadata and controls
74 lines (66 loc) · 1.88 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
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
import { useState } from "react";
import { Checkbox } from "./components/ui/checkbox";
interface ICheckboxes {
[key: string]: boolean;
selectAll: boolean;
india: boolean;
usa: boolean;
france: boolean;
}
const labels = new Map([
["selectAll", "Select all"],
["india", "India"],
["usa", "USA"],
["france", "France"],
]);
const initialState: ICheckboxes = {
selectAll: false,
india: false,
usa: false,
france: false,
};
function App() {
const [checkboxes, setCheckboxes] = useState(initialState);
const handleSelectAll = (
checked: boolean,
prevCheckboxes: ICheckboxes
): ICheckboxes =>
Object.keys(prevCheckboxes).reduce((acc, checkboxId) => {
acc[checkboxId] = checked;
return acc;
}, {} as ICheckboxes);
const handleIndividualCheckbox = (
updatedCheckboxes: ICheckboxes
): ICheckboxes => {
updatedCheckboxes.selectAll = Object.keys(updatedCheckboxes).every(
(checkboxId) =>
checkboxId === "selectAll" || updatedCheckboxes[checkboxId]
);
return updatedCheckboxes;
};
const handleCheckboxChange = (id: string) => (checked: boolean) => {
setCheckboxes((prevCheckboxes: ICheckboxes) => {
if (id === "selectAll") {
return handleSelectAll(checked, prevCheckboxes);
}
const updatedCheckboxes = { ...prevCheckboxes, [id]: checked };
return handleIndividualCheckbox(updatedCheckboxes);
});
};
return Object.entries(checkboxes).map(([id, checked]) => (
<div className="flex items-center content-start space-x-2 py-1" key={id}>
<Checkbox
id={id}
checked={checked}
onCheckedChange={handleCheckboxChange(id)}
/>
<label
htmlFor={id}
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{labels.get(id)}
</label>
</div>
));
}
export default App;