I have a function that receives values from a json that contains nested values (parent and children with multiple layers) and this function sets up a checkbox for each item, with its children below its respective parent.
I would like help when clicking on a parent checkbox, all the child checkboxes will be selected, when clicking on a child checkbox and the other children are not clicked, the parent element will have an "indeterminate" state, if there is only one child checkbox and it is clicked or all children are clicked the parent element is selected.
You can see the screenshot of how it should behave by clicking here.
Here you can see the project online.
CheckboxItem Component:
import { useState } from "react";
import Checkbox from "react-three-state-checkbox";
export function CheckboxItem(props) {
const [isChecked, setIsChecked] = useState(false);
function clickCheckbox() {
setIsChecked(!isChecked);
}
return (
<>
<Checkbox
checked={isChecked}
// indeterminate={props.indeterminate}
onChange={clickCheckbox}
/>
{props.children}
</>
);
}
ChildrenMap Component:
import { CheckboxItem } from "../CheckboxItem";
import * as S from "./styled";
export function ChildrenMap({ itens }) {
const filhos = Object.values(itens);
return (
<div>
{filhos.map((item, i) => (
<S.Itens key={i}>
<CheckboxItem>
{item.name}
</CheckboxItem>
<ChildrenMap itens={item.children} key={i} />
</S.Itens>
))}
</div>
);
}
Main File:
import React from "react";
import ReactDOM from "react-dom";
import { ChildrenMap } from "./components/ChildrenMap";
import data from "./data.json";
function App() {
return (
<>
{data.itens.map((item, i) => (
<div key={i}>
<ChildrenMap itens={item} key={i} />
</div>
))}
</>
);
}