I'm trying to build a nested checkbox with 2 levels using Chakra-UI.
- Once clicked on parent checkbox, all children should be checked: (v)
- if you click on one child, all parents should be on indeterminate state: (-)
- if all children are checked, the parent of these children should be checked as well.
The first level is already done here:
import React from "react";
import { Checkbox, Stack, Box } from "@chakra-ui/react";
const data = {
users: [
{
id: "user-1",
name: "User 1",
child: [{ name: "Salary1" }, { name: "Department1" }]
},
{
id: "user-2",
name: "User 2",
child: [{ name: "Salary2" }, { name: "Department2" }]
},
{
id: "user-3",
name: "User 3",
child: [{ name: "Salary3" }, { name: "Department3" }]
},
{
id: "user-4",
name: "User 4",
child: [{ name: "Salary4" }, { name: "Department4" }]
},
{
id: "user-5",
name: "User 5",
child: [{ name: "Salary5" }, { name: "Department5" }]
},
{
id: "user-6",
name: "User 6",
child: [{ name: "Salary6" }, { name: "Department6" }]
},
{
id: "user-7",
name: "User 7",
child: [{ name: "Salary7" }, { name: "Department7" }]
},
{
id: "user-8",
name: "User 8",
child: [{ name: "Salary8" }, { name: "Department8" }]
}
]
};
export default function App() {
const [checkedItems, setCheckedItems] = React.useState(
data.users.map(() => false)
);
const allChecked = checkedItems.every(Boolean);
const isIndeterminate = checkedItems.some(Boolean) && !allChecked;
return (
<Stack pt={3} pl={3}>
<Checkbox
isChecked={allChecked}
isIndeterminate={isIndeterminate}
onChange={(e) =>
setCheckedItems(data.users.map(() => e.target.checked))
}
>
Parent Checkbox
</Checkbox>
<Stack pl={6} mt={2} spacing={2}>
{data.users.map((user, index) => (
<Box key={user.id}>
<Checkbox
key={user.id}
isChecked={checkedItems[index]}
onChange={(e) =>
setCheckedItems([
...checkedItems.slice(0, index),
e.target.checked,
...checkedItems.slice(index + 1)
])
}
>
{user.name}
</Checkbox>
<Stack pl={6} spacing={2}>
{user.child.map((category) => (
<Checkbox key={category.name}>{category.name}</Checkbox>
))}
</Stack>
</Box>
))}
</Stack>
</Stack>
);
How could the level 2 be achieved using the starter code above? Any help would be greatly appreciated. Thanks in advance.
Here is the CodeSanbox link: https://codesandbox.io/s/peaceful-rosalind-741e5c?file=/src/App.js:0-2336
Aucun commentaire:
Enregistrer un commentaire