Nested Checkboxes

Autor
Ex-Meta Staff Engineer
Languages

Build a component that displays a hierarchical structure of checkboxes. The component should handle parent-child relationships between checkboxes and manage their states efficiently.

Requirements

  • A checkbox's value is determined by the value of its direct children:
    • When all children of a parent are checked, the parent should be checked.
    • When some (but not all or none) children of a parent are checked, the parent should be in an indeterminate state, with a dash displayed within the box.
    • When none of the children of a parent are checked, the parent is unchecked.
  • If a parent checkbox is checked or unchecked, all the descendant checkboxes (not just direct children) will be updated with that new value.
  • The focus of the exercise is on the functionality and not the styling. You may style the checkboxes in any way you prefer as long as the states are clear.

Data format

interface CheckboxItem {
  id: number;
  name: string;
  checked: boolean | 'indeterminate';
  children?: CheckboxItem[];
}

Example data:

const fileData = [
  {
    id: 1,
    name: 'Electronics',
    children: [
      {
        id: 2,
        name: 'Mobile phones',
        children: [
          {
            id: 3,
            name: 'iPhone',
          },
          {
            id: 4,
            name: 'Android',
          },
        ],
      },
      {
        id: 5,
        name: 'Laptops',
        children: [
          {
            id: 6,
            name: 'MacBook',
          },
          {
            id: 7,
            name: 'Surface Pro',
          },
        ],
      },
    ],
  },
  {
    id: 8,
    name: 'Books',
    children: [
      {
        id: 9,
        name: 'Fiction',
      },
      {
        id: 10,
        name: 'Non-fiction',
      },
    ],
  },
  {
    id: 11,
    name: 'Toys',
  },
];

Empresas

Recurso PremiumCompre o premium para ver quais empresas fazem essa pergunta.
Ver planos
View solution