My Learning Blog

Recursive component in React - 7/21/2024

Can be particularly useful for rendering hierarchical data structures like trees.

This example demonstrates how to create a recursive component to handle nested data structures, making it a powerful tool for dealing with hierarchical data in React.

const RecursiveList = ({ data }) => {
  if (!data || !data.length) {
    return null;
  }

  return (
    <ul>
      {data.map((item, index) => (
        <li key={index}>
          {item.name}
          {item.children && <RecursiveList data={item.children} />}
        </li>
      ))}
    </ul>
  );
};

export default RecursiveList;