@ratibordas
Frontend-статист

Как рекурсивно отрендерить массив с глубокой вложенностью с помощью map в React?

Нужно cделать так, чтобы каждый элемент массива рендерился в формате компонента с текстом из title и text, дочерние элементы по той же логике из значения массивов items. Сложность в том, что при маппинге, у перебираемых объектов нет children (undefined) и я просто не могу передать вложенность. Все решения, которые я нашел, основаны на рекурсии с передачей 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>
        </>
       ) 
}
  • Вопрос задан
  • 414 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега React
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;
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@afanasiyz
Javascript-разработчик
У вас сам компонент Item должен принимать объект item. title и text оттуда рендерить, а по полю items проходиться мапом и так же рендерить компонент Item, то есть рекурсивно.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы