Answer the question
In order to leave comments, you need to log in
How to recursively render a deeply nested array with map in React?
Good day! You need to make sure that each element of the array is rendered in the format of a component with text from title and text , child elements in the same logic from the value of the items arrays. The difficulty is that when mapping, the enumerated objects do not have children (undefined) and I simply cannot pass the nesting. All the solutions I found are based on recursion passing children
const Items = ({items}) => {
const items = [
{
title: 'Elements',
items: [
{
title: '1',
text: 'This is First one.',
items: [
{
title: '1:1',
text: 'This is First of the First one.',
items: [
{ title: '1:1:1', text: 'This is First of the First of the First one.' },
{ title: '1:1:2', text: 'This is Second of the First of the First one.', }
]
},
{
title: '1:2',
text: 'This is Second of the First one.',
items: [
{ title: '1:2:1', text: 'This is First of the Second of the First one.' },
{ title: '1:2:2', text: 'This is Second of the Second of the First one.' },
{ title: '1:2:3', text: 'This is Third of the Second of the First one.' },
]
},
]
},
{
title: '2',
text: 'This is Second one.',
items: [
{
title: '2:1',
text: 'This is First of the Second one.',
items: [
{ title: '2:1:1', text: 'This is First of the First of the Second one.' },
{ title: '2:1:2', text: 'This is Second of the First of the Second one.' }
]
}
]
},
{
title: '3',
text: 'This is Third one.'
}
]
}
];
return (
<>
{
items.map((item) => {
if (typeof(item) === Object) {
return (
<Items items={item.children}/>
)
}
return (
<Item item={item} />
)
})
}
</>
)
}
const Item = ({item}) => {
return (
<>
<h2>{item.title}</h2>
<p>{item.text}</p>
</>
)
}
Answer the question
In order to leave comments, you need to log in
const Items = ({ items }) =>
Array.isArray(items) && items.length
? <ul>
{items.map(n => (
<li>
<h2>{n.title}</h2>
<p>{n.text}</p>
<Items items={n.items} />
</li>
))}
</ul>
: null;
Your Item component itself must accept an item object. title and text are rendered from there, and the map is passed through the items field and the Item component is also rendered, that is, recursively.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question