Write a recursive CategoryTree that renders nested categories
Write CategoryTree. It takes categories, an array of objects like { id: 1, name: "Drinks", children: [...] }, where children holds more categories of the same shape, to any depth, and may be missing or empty.
Render a <ul> with one <li> per category. A category with children shows its name and, in brackets, how many categories are below it at every depth, like Drinks (4), followed by a nested <ul> of its children, drawn the same way. A category without children shows only its name, with no count and no nested list. When categories is empty, render nothing.
const categories = [
{
id: 1,
name: "Drinks",
children: [
{ id: 2, name: "Tea", children: [{ id: 3, name: "Green" }, { id: 4, name: "Black" }] },
{ id: 5, name: "Coffee", children: [] },
],
},
{ id: 6, name: "Cakes" },
];
// Drinks (4)
// Tea (2)
// Green
// Black
// Coffee
// Cakes
export default function CategoryTree({ categories }) {
return (
<ul>
{categories.map((category) => (
<li key={category.id}>{category.name}</li>
))}
</ul>
);
}
- nests each category's children inside its item
- counts the categories below at every depth
- leaves out the count and the list when there are no children
- goes to any depth
- renders nothing for no categories
- doesn't warn about keys
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…