Skip to content

pansinm/react-file-tree

Repository files navigation

react-file-tree

Online Demo

Install

yarn add @sinm/react-file-tree

Usage

  1. Render tree
import { FileTree } from '@sinm/react-file-tree';
// default style
import '@sinm/react-file-tree/styles.css';

const [tree, setTree] = useState(defaultTree);

<FileTree tree={tree}>
  1. Toggle expanded
import { utils } from "@sinm/react-file-tree";

const toggleExpanded: FileTreeProps["onItemClick"] = (treeNode) => {
  setTree((tree) =>
    utils.assignTreeNode(tree, treeNode.uri, { expanded: !treeNode.expanded })
  );
};

<FileTree tree={tree} onItemClick={toggleExpanded} />;
  1. use github-file-icons
import FileItemWithFileIcon from '@sinm/react-file-tree/lib/FileItemWithFileIcon';
// import { getFileIconClass } from '@sinm/react-file-tree/lib/FileItemWithFileIcon';
import '@sinm/react-file-tree/icons.css';
const itemRenderer = (treeNode: TreeNode) => <FileItemWithFileIcon treeNode={treeNode} />

<FileTree tree={tree} itemRenderer={itemRenderer} />
  1. Sort tree items
import orderBy from "lodash/orderBy";

// directory first and filename dict sort
const sorter = (treeNodes: TreeNode[]) =>
  orderBy(
    treeNodes,
    [
      (node) => (node.type === "directory" ? 0 : 1),
      (node) => utils.getFileName(node.uri),
    ],
    ["asc", "asc"]
  );

<FileTree tree={tree} sorter={sorter} />
  1. Load tree from server
// backend
import { getTreeNode } from "@sinm/react-file-tree/lib/node";

app.get("/root", async (req, res, next) => {
  try {
    const tree = await getTreeNode("."); // build tree for current directory
    res.send(tree);
  } catch (err) {
    next(err);
  }
});

// frontend
useEffect(() => {
  fetch("/root")
    .then((res) => res.json())
    // expand root node
    .then((tree) => Object.assign(tree, { expanded: true }))
    .then(setTree);
}, []);
  1. activated style
.file-tree__tree-item.activated {
  background: rgba(0, 0, 0, 0.1);
}
<FileTree tree={tree} activatedUri={uri}>

Props

  1. tree: TreeNode. Below is the TreeNode type,Examples can be found at https://codesandbox.io/s/react-file-tree-demo-yc52pj?file=/src/tree.json
export type TreeNodeType = "directory" | "file";

export type TreeNode<T extends {} = {}, K extends keyof T = keyof T> = {
  [x in K]: T[K];
} & {
  type: TreeNodeType;
  uri: string;
  expanded?: boolean;
  children?: TreeNode<T, K>[];
};
  1. activatedUri: string
  2. onItemClick(treeNode: TreeNode):void
  3. itemRenderer(treeNode: TreeNode): React.Element
  4. sorter: (treeNodes: TreeNode[]) => TreeNode[]

Demo

git clone https://github.com/pansinm/react-file-tree.git
cd react-file-tree
yarn
git submodule update --init --recursive
yarn start