Directory tree (single selection)
An example of how to customize the styling of the component
- src
- node_modules
- .npmignore
- package.json
- webpack.config.js
import React from "react";
import { DiCss3, DiJavascript, DiNpm } from "react-icons/di";
import { FaList, FaRegFolder, FaRegFolderOpen } from "react-icons/fa";
import TreeView, { flattenTree } from "react-accessible-treeview";
import "./styles.css";
const folder = {
name: "",
children: [
{
name: "src",
children: [{ name: "index.js" }, { name: "styles.css" }],
},
{
name: "node_modules",
children: [
{
name: "react-accessible-treeview",
children: [{ name: "index.js" }],
},
{ name: "react", children: [{ name: "index.js" }] },
],
},
{
name: ".npmignore",
},
{
name: "package.json",
},
{
name: "webpack.config.js",
},
],
};
const data = flattenTree(folder);
function DirectoryTreeView() {
return (
<div>
<div className="directory">
<TreeView
data={data}
aria-label="directory tree"
nodeRenderer={({
element,
isBranch,
isExpanded,
getNodeProps,
level,
}) => (
<div {...getNodeProps()} style={{ paddingLeft: 20 * (level - 1) }}>
{isBranch ? (
<FolderIcon isOpen={isExpanded} />
) : (
<FileIcon filename={element.name} />
)}
{element.name}
</div>
)}
/>
</div>
</div>
);
}
const FolderIcon = ({ isOpen }) =>
isOpen ? (
<FaRegFolderOpen color="e8a87c" className="icon" />
) : (
<FaRegFolder color="e8a87c" className="icon" />
);
const FileIcon = ({ filename }) => {
const extension = filename.slice(filename.lastIndexOf(".") + 1);
switch (extension) {
case "js":
return <DiJavascript color="yellow" className="icon" />;
case "css":
return <DiCss3 color="turquoise" className="icon" />;
case "json":
return <FaList color="yellow" className="icon" />;
case "npmignore":
return <DiNpm color="red" className="icon" />;
default:
return null;
}
};
export default DirectoryTreeView;
.directory {
background: #242322;
font-family: monospace;
font-size: 16px;
color: white;
user-select: none;
padding: 20px;
border-radius: 0.4em;
}
.directory .tree,
.directory .tree-node,
.directory .tree-node-group {
list-style: none;
margin: 0;
padding: 0;
}
.directory .tree-branch-wrapper,
.directory .tree-node__leaf {
outline: none;
outline: none;
}
.directory .tree-node {
cursor: pointer;
}
.directory .tree-node:hover {
background: rgba(255, 255, 255, 0.1);
}
.directory .tree .tree-node--focused {
background: rgba(255, 255, 255, 0.2);
}
.directory .tree .tree-node--selected {
background: rgba(48, 107, 176);
}
.directory .tree-node__branch {
display: block;
}
.directory .icon {
vertical-align: middle;
padding-right: 5px;
}