I am online
← Back to Articles

Rendering React Components Recursively

ReactjsJune 29, 2024

React components are just functions.

Recursion can be useful when dealing with nested structures like folder and file trees.

This approach keeps your code clean and manageable, especially when dealing with deeply nested data.

Make sure to handle base condition to avoid infinite recursion. In this case, check if the node is a folder and only then render its children.

export default function Folder({ node }) {
  return (
    <>
      <div>
        {node.isFolder ? "🗂" : "📄"} {node.name}
      </div>
      {node.isFolder &&
        node.children.map((child) => <Folder key={child.id} node={child} />)}
    </>
  );
}

Happy coding!