Sobes.tech
Junior — Senior

React component for displaying comments with arbitrary nesting depth

livecode

Task condition

It is required to create a React component Comments that receives a single prop — an array of comments (comments). Each element of the array is an object with mandatory properties id and text. Additionally, the object can contain an optional property children — an array of nested comments of the same format. The component must render a list of comments, displaying the text of each element. If a comment has a children array, its elements should be displayed as a nested list under the corresponding parent item. The nesting of comments can be of any depth, with no restrictions.

import React from "react";

let comments = [
  {
    id: 1,
    text: "message 1",
  },
  {
    id: 2,
    text: "message 2",
    children: [
      {
        id: 4,
        text: "message 4",
        children: [
          {
            id: 7,
            text: "message 7",
          },
          {
            id: 8,
            text: "message 8",
            children: [
              {
                id: 9,
                text: "message 9",
              },
              {
                id: 10,
                text: "message 10",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 5,
    text: "message 5",
  },
];

const App = () => {
  return (
    <div className="App">
      <Comments comments={comments} />
    </div>
  );
};

export default App;

The component should recursively traverse the data structure and correctly display any levels of nesting, using nested lists or any other suitable markup elements.