Ai: Display tree structure in React from a list of file paths
Overview
I have been searching on Google on how to display a tree structure in React from a list of file paths. I tried different npm packages and libraries but in vain. After trial and error for an hour, Google Gemini gave me a perfect solution. Even though it labeled the example as conceptual javascript, it is a perfect running and working implementation. I'm really amazed.
Gemini solution
The only part I have to write is the create a React page using Gemini's codes.
import React, { useState } from 'react';
function pathsToTreeNode(filePaths) {
const tree = { name: 'root', children: [] };
filePaths.forEach(path => {
const parts = path.split('/'); // Assuming '/' as path separator
let currentLevel = tree.children;
parts.forEach((part, index) => {
let existingNode = currentLevel.find(node => node.name === part);
if (!existingNode) {
existingNode = { name: part };
if (index < parts.length - 1) { // It's a directory
existingNode.children = [];
}
currentLevel.push(existingNode);
}
currentLevel = existingNode.children;
});
});
return tree;
}
const TreeNode = ({ node }) => {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => {
setIsExpanded(!isExpanded);
};
return (
<div>
<span onClick={node.children ? toggleExpand : null}>
{node.children && (isExpanded ? 'â–¼ ' : 'â–º ')}
{node.name}
</span>
{node.children && isExpanded && (
<div style={{ marginLeft: '20px' }}>
{node.children.map((child, index) => (
<TreeNode key={index} node={child} />
))}
</div>
)}
</div>
);
};
const FileTree = ({ filePaths }) => {
const treeData = pathsToTreeNode(filePaths); // Use the function from step 1
return (
<div>
{treeData.children.map((node, index) => (
<TreeNode key={index} node={node} />
))}
</div>
);
};
/**
* This is the only part that I wrote.
* Create a React page using Gemini solution.
*/
export default function Tree() {
const listOfFilePaths = [
'_readme.sh',
'xPuppeteer.mjs',
'xPuppeteer.usage.mjs',
'xSql.mjs',
'xWeek.mjs',
'react/xMarkdown.jsx',
'react/deprecated/xMarked.jsx'
]
return (
<FileTree filePaths={listOfFilePaths} />
);
}
Gemini Explanation
To display a tree structure in React based on a list of file paths, you need to first convert the flat list of paths into a hierarchical data structure, and then render that structure using React components, often recursively.
-
Converting File Paths to a Tree Structure: You can achieve this by iterating through the file paths and building a nested object or array structure. Each path component (directory or file name) becomes a node in the tree.
- Algorithm:
- Initialize an empty root node for your tree.
- For each file path in your list:
- Split the path into its individual components (e.g., src/components/Button.js becomes ['src', 'components', 'Button.js']).
- Traverse your tree structure, adding new directory nodes if they don't exist.
- At the end of the path, add the file as a leaf node.
- Algorithm:
-
Rendering the Tree in React: You can create a recursive React component to render the tree structure.
- Recursive Component Design:
- Create a TreeNode component that accepts a node prop (representing a directory or file).
- Inside TreeNode, conditionally render its children if the node is a directory and is expanded.
- Map over the children array and render another TreeNode component for each child.
- Manage the expansion/collapse state of directories using React's useState hook.
- Recursive Component Design: