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.
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} />
);
}
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.
Rendering the Tree in React: You can create a recursive React component to render the tree structure.