Rekurencyjne wyświetlenie komentarzy

0

Cześć, spotkał się ktoś może z problemem wyświetlenia rekurencyjnie listy z zagnieżdżeniem bazując na parentID?

Mam tablicę komentarzy:

[
{ title: "Title", content: "Treść", id: 1, parentId: 0},
{ title: "Title", content: "Treść", id: 2, parentId: 1},
{ title: "Title", content: "Treść", id: 3, parentId: 2},
{ title: "Title", content: "Treść", id: 4, parentId: 0},
{ title: "Title", content: "Treść", id: 5, parentId: 2},
]

I teraz muszę wyświetlić drzewko w taki sposób

-id1
----id2
-------id3
-------id5
-id4

Ma ktoś na to jakiś sposób? Sprawa tyczy się reacta

0
import React, { useState } from "react";

const data = [
  { title: "Title", content: "Treść", id: 1, parentId: 0},
  { title: "Title", content: "Treść", id: 2, parentId: 1},
  { title: "Title", content: "Treść", id: 3, parentId: 2},
  { title: "Title", content: "Treść", id: 4, parentId: 0},
  { title: "Title", content: "Treść", id: 5, parentId: 2},
]

function Comment({ title, id, comments, content }) {
  const children = comments.filter((comment) => comment.parentId === id)
  return (
    <div style={{paddingLeft: 20}}>
      <h2>{title} {id}</h2>
      <div>{content}</div>
      { children.length > 0 && children
      .map((comment) => <Comment 
        comments={comments}
        content={comment.content}
        title={comment.title}
        id={comment.id}
        key={comment.id}
      />)}
    </div>
    
  )
}

export default function App() {
  const [comments] = useState(data);
  return (
    <div>
      { comments && comments
      .filter((comment) => comment.parentId === 0)
      .map((comment) => <Comment
        comments={comments}
        content={comment.content}
        title={comment.title}
        id={comment.id}
        key={comment.id}
      />)
      }
    </div>
  );
}

demo: https://stackblitz.com/edit/react-p3mwsd?file=src/App.js

1 użytkowników online, w tym zalogowanych: 0, gości: 1