0

I have an object similar to this:

{
    id: number,
    kids: [{
        id: number,
        kids: [{
            id: number,
            kids: []
        }]
    }]
}

So it has property kids which is an array of kids each of which might have its own array of kids. I need to render original object in a tree view list like this:

<ul>
  {object.map(item => (
    <li>
      <p>{item.value}</p>
      {item.kids ?
        {item.kids.map(item => (
          <ul>
            <li>
              <p>{item.value}</p>
            </li>
          </ul>
        ))}
        : null
      }
    </li>
  ))}
</ul>

So every item of kids will be a <li></li> element with <ul></ul> inside of it if item.kids isn't empty array. I could keep going like this but it's pretty messy and more importantly I don't know when exactly kids property will be an empty array. So I need somehow loop over original object and it's properties and do something like

while (kid.kids) {
  return {kid.kids.map(kid => (
           <li>
             <p>{kid.value}</p>
             <ul>
               kid.kids.map(kid => (
                 etc
               ))
             </ul>
           </li>
         }))
}

But I can't understand the better way to loop like this.

1
  • 1
    Could you draw a picture to better describe your expected output? Thanks! Also, I'd recommend reading How do I ask a good question and taking the tour! These articles will help you get the best answers!
    – Rojo
    Commented Dec 13, 2020 at 15:26

1 Answer 1

4

This is probably best solved with recursion.

const Kids = ({id, kids}) => {
    return {
        <li key={id}>
            <p>{id}</p>
            {kids 
                ? (<ul>{kids.map((kid) => <Kids id={kid.id} kids={kid.kids} />)}</ul>)
                : null; 
            }
        </li>
    }
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.