How to iterate over all children elements?
I have an array that has an infinite number of nested childrens, how do I output all of them?
const data = [ { title: "Mark", children: [{ title: "Alex" }] }, { title: "Alisa", children: [{ title: "Bob", children: [{ title: "Jacob" }] }] } ];
I only go through two levels, but there can be as many as you like.
{data.map((item) => { return ( <div> {item.title} {item.children.map((item) => item.title)} </div> ); })}
Advertisement
Answer
Make the mapper a named function, and then you’ll be able to call it recursively.
const renderItem = item => ( <div> {item.title} {item.children?.map(renderItem)} </div> ); return data.map(renderItem);