React Arborist

The complete tree view component for React

README

Logo

React Arborist



The tree view is ubiquitous in software applications. This library provides the React ecosystem with a complete solution to build the equivalent of a VSCode sidebar, Mac Finder, Windows Explorer, or Sketch/Figma layers panel.

Here is a Gmail sidebar clone built with react-arborist.

Gmail sidebar clone built with react-arborist

Features


- Drag and drop sorting
- Open/close folders
- Inline renaming
- Virtualized rendering
- Custom styling
- Keyboard navigation
- Aria attributes
- Tree filtering
- Selection synchronization
- Callbacks (onScroll, onActivate, onSelect)
- Controlled or uncontrolled trees

Installation


  1. ```
  2. yarn add react-arborist
  3. ```

  1. ```
  2. npm install react-arborist
  3. ```

Examples


Assume our data is this:

  1. ```js
  2. const data = [
  3.   { id: "1", name: "Unread" },
  4.   { id: "2", name: "Threads" },
  5.   {
  6.     id: "3",
  7.     name: "Chat Rooms",
  8.     children: [
  9.       { id: "c1", name: "General" },
  10.       { id: "c2", name: "Random" },
  11.       { id: "c3", name: "Open Source Projects" },
  12.     ],
  13.   },
  14.   {
  15.     id: "4",
  16.     name: "Direct Messages",
  17.     children: [
  18.       { id: "d1", name: "Alice" },
  19.       { id: "d2", name: "Bob" },
  20.       { id: "d3", name: "Charlie" },
  21.     ],
  22.   },
  23. ];
  24. ```

The Simplest Tree


Use all the defaults. The _initialData_ prop makes the tree an uncontrolled component. Create, move, rename, and delete will be handled internally.

  1. ```jsx
  2. function App() {
  3.   return <Tree initialData={data} />;
  4. }
  5. ```

image


Customize the Appearance


We provide our own dimensions and our own Node component.

  1. ```jsx
  2. function App() {
  3.   return (
  4.     <Tree
  5.       initialData={data}
  6.       openByDefault={false}
  7.       width={600}
  8.       height={1000}
  9.       indent={24}
  10.       rowHeight={36}
  11.       overscanCount={1}
  12.       paddingTop={30}
  13.       paddingBottom={10}
  14.       padding={25 /* sets both */}
  15.     >
  16.       {Node}
  17.     </Tree>
  18.   );
  19. }

  20. function Node({ node, style, dragHandle }) {
  21.   /* This node instance can do many things. See the API reference. */
  22.   return (
  23.     <div style={style} ref={dragHandle}>
  24.       {node.isLeaf ? "🍁" : "🗀"}
  25.       {node.data.name}
  26.     </div>
  27.   );
  28. }
  29. ```

image


Control the Tree data


Here we use the _data_ prop to make the tree a controlled component. We must handle all the data modifications ourselves using the props below.

  1. ```jsx
  2. function App() {
  3.   /* Handle the data modifications outside the tree component */
  4.   const onCreate = ({ parentId, index, type }) => {};
  5.   const onRename = ({ id, name }) => {};
  6.   const onMove = ({ dragIds, parentId, index }) => {};
  7.   const onDelete = ({ ids }) => {};

  8.   return (
  9.     <Tree
  10.       data={data}
  11.       onCreate={onCreate}
  12.       onRename={onRename}
  13.       onMove={onMove}
  14.       onDelete={onDelete}
  15.     />
  16.   );
  17. }
  18. ```

Tree Filtering


Providing a non-empty _searchTerm_ will only show nodes that match. If a child matches, all its parents also match. Internal nodes are opened when filtering. You can provide your own _searchMatch_ function, or use the default.

  1. ```jsx
  2. function App() {
  3.   const term = useSearchTermString()
  4.   <Tree
  5.     data={data}
  6.     searchTerm={term}
  7.     searchMatch={
  8.       (node, term) => node.data.name.toLowerCase().includes(term.toLowerCase())
  9.     }
  10.   />
  11. }
  12. ```

Sync the Selection


It's common to open something elsewhere in the app, but have the tree reflect the new selection.

Passing an id to the _selection_ prop will select and scroll to that node whenever that id changes.

  1. ```jsx
  2. function App() {
  3.   const chatId = useCurrentChatId();

  4.   /*
  5.     Whenever the currentChatRoomId changes,
  6.     the tree will automatically select it and scroll to it.
  7.   */

  8.   return <Tree initialData={data} selection={chatId} />;
  9. }
  10. ```

Use the Tree Api Instance


You can access the Tree Api in the parent component by giving a ref to the tree.

  1. ```jsx
  2. function App() {
  3.   const treeRef = useRef();

  4.   useEffect(() => {
  5.     const tree = treeRef.current;
  6.     tree.selectAll();
  7.     /* See the Tree API reference for all you can do with it. */
  8.   }, []);

  9.   return <Tree initialData={data} ref={treeRef} />;
  10. }
  11. ```

Data with Different Property Names


The _idAccessor_ and _childrenAccessor_ props allow you to specify the children and id fields in your data.

  1. ```jsx
  2. function App() {
  3.   const data = [
  4.     {
  5.       category: "Food",
  6.       subCategories: [{ category: "Restaurants" }, { category: "Groceries" }],
  7.     },
  8.   ];
  9.   return (
  10.     <Tree
  11.       data={data}
  12.       /* An accessor can provide a string property name */
  13.       idAccessor="category"
  14.       /* or a function with the data as the argument */
  15.       childrenAccessor={(d) => d.subCategories}
  16.     />
  17.   );
  18. }
  19. ```

Custom Rendering


Render every single piece of the tree yourself. See the API reference for the props passed to each renderer.

  1. ```jsx
  2. function App() {
  3.   return (
  4.     <Tree
  5.       data={data}
  6.       /* The outer most element in the list */
  7.       renderRow={MyRow}
  8.       /* The "ghost" element that follows the mouse as you drag */
  9.       renderDragPreview={MyDragPreview}
  10.       /* The line that shows where an element will be dropped */
  11.       renderCursor={MyCursor}
  12.     >
  13.       {/* The inner element that shows the indentation and data */}
  14.       {MyNode}
  15.     </Tree>
  16.   );
  17. }
  18. ```

API Reference


- Components
- Interfaces
  - Node API
  - Tree API

Tree Component Props


These are all the props you can pass to the Tree component.

  1. ```ts
  2. interface TreeProps<T> {
  3.   /* Data Options */
  4.   data?: readonly T[];
  5.   initialData?: readonly T[];

  6.   /* Data Handlers */
  7.   onCreate?: handlers.CreateHandler<T>;
  8.   onMove?: handlers.MoveHandler<T>;
  9.   onRename?: handlers.RenameHandler<T>;
  10.   onDelete?: handlers.DeleteHandler<T>;

  11.   /* Renderers*/
  12.   children?: ElementType<renderers.NodeRendererProps<T>>;
  13.   renderRow?: ElementType<renderers.RowRendererProps<T>>;
  14.   renderDragPreview?: ElementType<renderers.DragPreviewProps>;
  15.   renderCursor?: ElementType<renderers.CursorProps>;
  16.   renderContainer?: ElementType<{}>;

  17.   /* Sizes */
  18.   rowHeight?: number;
  19.   overscanCount?: number;
  20.   width?: number | string;
  21.   height?: number;
  22.   indent?: number;
  23.   paddingTop?: number;
  24.   paddingBottom?: number;
  25.   padding?: number;

  26.   /* Config */
  27.   childrenAccessor?: string | ((d: T) => T[] | null);
  28.   idAccessor?: string | ((d: T) => string);
  29.   openByDefault?: boolean;
  30.   selectionFollowsFocus?: boolean;
  31.   disableMultiSelection?: boolean;
  32.   disableEdit?: string | boolean | BoolFunc<T>;
  33.   disableDrag?: string | boolean | BoolFunc<T>;
  34.   disableDrop?:
  35.     | string
  36.     | boolean
  37.     | ((args: {
  38.         parentNode: NodeApi<T>;
  39.         dragNodes: NodeApi<T>[];
  40.         index: number;
  41.       }) => boolean);

  42.   /* Event Handlers */
  43.   onActivate?: (node: NodeApi<T>) => void;
  44.   onSelect?: (nodes: NodeApi<T>[]) => void;
  45.   onScroll?: (props: ListOnScrollProps) => void;
  46.   onToggle?: (id: string) => void;
  47.   onFocus?: (node: NodeApi<T>) => void;

  48.   /* Selection */
  49.   selection?: string;

  50.   /* Open State */
  51.   initialOpenState?: OpenMap;

  52.   /* Search */
  53.   searchTerm?: string;
  54.   searchMatch?: (node: NodeApi<T>, searchTerm: string) => boolean;

  55.   /* Extra */
  56.   className?: string | undefined;
  57.   rowClassName?: string | undefined;

  58.   dndRootElement?: globalThis.Node | null;
  59.   onClick?: MouseEventHandler;
  60.   onContextMenu?: MouseEventHandler;
  61.   dndManager?: DragDropManager;
  62. }
  63. ```

Row Component Props


The _\_ is responsible for attaching the drop ref, the row style (top, height) and the aria-attributes. The default should work fine for most use cases, but it can be replaced by your own component if you need. See the _renderRow_ prop in the _\_ component.

  1. ```ts
  2. type RowRendererProps<T> = {
  3.   node: NodeApi<T>;
  4.   innerRef: (el: HTMLDivElement | null) => void;
  5.   attrs: HTMLAttributes<any>;
  6.   children: ReactElement;
  7. };
  8. ```

Node Component Props


The _\_ is responsible for attaching the drag ref, the node style (padding for indentation), the visual look of the node, the edit input of the node, and anything else you can dream up.

There is a default renderer, but it's only there as a placeholder to get started. You'll want to create your own component for this. It is passed as the _\_ components only child.

  1. ```ts
  2. export type NodeRendererProps<T> = {
  3.   style: CSSProperties;
  4.   node: NodeApi<T>;
  5.   tree: TreeApi<T>;
  6.   dragHandle?: (el: HTMLDivElement | null) => void;
  7.   preview?: boolean;
  8. };
  9. ```

DragPreview Component Props


The _\_ is responsible for showing a "ghost" version of the node being dragged. The default is a semi-transparent version of the NodeRenderer and should work fine for most people. To customize it, pass your new component to the _renderDragPreview_ prop.

  1. ```ts
  2. type DragPreviewProps = {
  3.   offset: XYCoord | null;
  4.   mouse: XYCoord | null;
  5.   id: string | null;
  6.   dragIds: string[];
  7.   isDragging: boolean;
  8. };
  9. ```

Cursor Component Props


The _\_ is responsible for showing a line that indicates where the node will move to when it's dropped. The default is a blue line with circle on the left side. You may want to customize this. Pass your own component to the _renderCursor_ prop.

  1. ```ts
  2. export type CursorProps = {
  3.   top: number;
  4.   left: number;
  5.   indent: number;
  6. };
  7. ```

Node API Reference


State Properties


All these properties on the node instance return booleans related to the state of the node.

_node_.isRoot

Returns true if this is the root node. The root node is added internally by react-arborist and not shown in the UI.

_node_.isLeaf

Returns true if the children property is not an array.

_node_.isInternal

Returns true if the children property is an array.

_node_.isOpen

Returns true if node is internal and in an open state.

_node_.isEditing

Returns true if this node is currently being edited. Use this property in the NodeRenderer to render the rename form.

_node_.isSelected

Returns true if node is selected.

_node_.isSelectedStart

Returns true if node is the first of a contiguous group of selected nodes. Useful for styling.

_node_.isSelectedEnd

Returns true if node is the last of a contiguous group of selected nodes. Useful for styling.

_node_.isOnlySelection

Returns true if node is the only node selected in the tree.

_node_.isFocused

Returns true if node is focused.

_node_.isDragging

Returns true if node is being dragged.

_node_.willReceiveDrop

Returns true if node is internal and the user is hovering a dragged node over it.

_node_.state

Returns an object with all the above properties as keys and boolean values. Useful for adding class names to an element with a library like clsx or classnames.

  1. ```ts
  2. type NodeState = {
  3.   isEditing: boolean;
  4.   isDragging: boolean;
  5.   isSelected: boolean;
  6.   isSelectedStart: boolean;
  7.   isSelectedEnd: boolean;
  8.   isFocused: boolean;
  9.   isOpen: boolean;
  10.   isClosed: boolean;
  11.   isLeaf: boolean;
  12.   isInternal: boolean;
  13.   willReceiveDrop: boolean;
  14. };
  15. ```

Accessors


_node_.childIndex

Returns the node's index in relation to its siblings.

_node_.next

Returns the next visible node. The node directly under this node in the tree component. Returns null if none exist.

_node_.prev

Returns the previous visible node. The node directly above this node in the tree component. Returns null if none exist.

_node_.nextSibling

Returns the next sibling in the data of this node. Returns null if none exist.

Selection Methods


_node_.select()

Select only this node.

_node_.deselect()

Deselect this node. Other nodes may still be selected.

_node_.selectMulti()

Select this node while maintaining all other selections.

_node_.selectContiguous()

Deselect all nodes from the anchor node to the last selected node, the select all nodes from the anchor node to this node. The anchor changes to the focused node after calling _select()_ or _selectMulti()_.

Activation Methods


_node_.activate()

Runs the Tree props' onActivate callback passing in this node.

_node_.focus()

Focus this node.

Open/Close Methods


_node_.open()

Opens the node if it is an internal node.

_node_.close()

Closes the node if it is an internal node.

_node_.toggle()

Toggles the open/closed state of the node if it is an internal node.

_node_.openParents()

Opens all the parents of this node.

_node_.edit()

Moves this node into the editing state. Calling node._isEditing_ will return true.

_node_.submit(_newName_)

Submits _newName_ string to the _onRename_ handler. Moves this node out of the editing state.

_node_.reset()

Moves this node out of the editing state without submitting a new name.

Event Handlers


_node_.handleClick(_event_)

Useful for using the standard selection methods when a node is clicked. If the meta key is down, call _multiSelect()_. If the shift key is down, call _selectContiguous()_. Otherwise, call _select()_ and _activate()_.

Tree API Reference


The tree api reference is stable across re-renders. It always has the most recent state and props.

Node Accessors


_tree_.get(_id_) : _NodeApi | null_

Get node by id from the _visibleNodes_ array.

_tree_.at(_index_) : _NodeApi | null_

Get node by index from the _visibleNodes_ array.

_tree_.visibleNodes : _NodeApi[]_

Returns an array of the visible nodes.

_tree_.firstNode : _NodeApi | null_

The first node in the _visibleNodes_ array.

_tree_.lastNode : _NodeApi | null_

The last node in the _visibleNodes_ array.

_tree_.focusedNode : _NodeApi | null_

The currently focused node.

_tree_.mostRecentNode : _NodeApi | null_

The most recently selected node.

_tree_.nextNode : _NodeApi | null_

The node directly after the _focusedNode_ in the _visibleNodes_ array.

_tree_.prevNode : _NodeApi | null_

The node directly before the _focusedNode_ in the _visibleNodes_ array.

Focus Methods


_tree_.hasFocus : _boolean_

Returns true if the the tree has focus somewhere within it.

_tree_.focus(_id_)

Focus on the node with _id_.

_tree_.isFocused(_id_) : _boolean_

Check if the node with _id_ is focused.

_tree_.pageUp()

Move focus up one page.

_tree_.pageDown()

Move focus down one page.

Selection Methods


_tree_.**selectedIds** : _Set\_

Returns a set of ids that are selected.

_tree_.selectedNodes : _NodeApi[]_

Returns an array of nodes that are selected.

_tree_.hasNoSelection : boolean

Returns true if nothing is selected in the tree.

_tree_.hasSingleSelection : boolean

Returns true if there is only one selection.

_tree_.hasMultipleSelections : boolean

Returns true if there is more than one selection.

_tree_.isSelected(_id_) : _boolean_

Returns true if the node with _id_ is selected.

_tree_.select(_id_)

Select only the node with _id_.

_tree_.deselect(_id_)

Deselect the node with _id_.

_tree_.selectMulti(_id_)

Add to the selection the node with _id_.

_tree_.selectContiguous(_id_)

Deselected nodes between the anchor and the last selected node, then select the nodes between the anchor and the node with _id_.

_tree_.deselectAll()

Deselect all nodes.

_tree_.selectAll()

Select all nodes.

Visibility


_tree_.open(_id_)

Open the node with _id_.

_tree_.close(_id_)

Close the node with _id_.

_tree_.toggle(_id_)

Toggle the open state of the node with _id_.

_tree_.openParents(_id_)

Open all parents of the node with _id_.

_tree_.openSiblings(_id_)

Open all siblings of the node with _id_.

_tree_.openAll()

Open all internal nodes.

_tree_.closeAll()

Close all internal nodes.

_tree_.isOpen(_id_) : _boolean_

Returns true if the node with _id_ is open.

Drag and Drop


_tree_.isDragging(_id_) : _boolean_

Returns true if the node with _id_ is being dragged.

_tree_.willReceiveDrop(_id_) : _boolean_

Returns true if the node with _id_ is internal and is under the dragged node.

Scrolling


_tree_.scrollTo(_id_, _[align]_)

Scroll to the node with _id_. If this node is not visible, this method will open all its parents. The align argument can be _"auto" | "smart" | "center" | "end" | "start"_.

Properties


_tree_.isEditing : _boolean_

Returns true if the tree is editing a node.

_tree_.isFiltered : _boolean_

Returns true if the _searchTerm_ prop is not an empty string when trimmed.

_tree_.props : _TreeProps_

Returns all the props that were passed to the _\_ component.

_tree_.root : _NodeApi_

Returns the root _NodeApi_ instance. Its children are the Node representations of the _data_ prop array.

Author