Skip to main content

Tree

Version

This component builds out a hierarchical tree of objects, with the ability to expand/collapse, select, and search.

Installation

npm

npm install @availity/tree

Yarn

yarn add @availity/tree

Usage

Example

import React from 'react';
import Tree, { buildTree, TreeItem } from '@availity/tree';

const Example = ({ myData }: Props) => (
const [valueList, setValueList] = useState<TreeItem[]>([]);
const [tree, setTree] = useState<TreeItem[]>([]);
const [initialState, setInitialState] = useState<TreeItem[]>([]);

const onSelected = (selectedItems: TreeItem[]) => {
setTentativeSelectList(selectedItems.map((item) => ({ code: item.id, value: item.name })));
};

const reset = () => {
setTentativeSelectList([]);
setTree(cloneDeep(initialState));
};

useEffect(() => {
// buildTree will construct a list of TreeItems as expected by the tree component
// this optionally allows you to pass an array of expandedIds and selectedIds
const tree = buildTree(myData, expandedIds, selectedIds);
await setInitialState(cloneDeep(tree));
await setTree(tree);
}, []);

return (
<>
<Tree
items={tree}
expandAll
enableSearch
selectedItems={valueList}
onItemsSelected={onSelected}
/>
<Button id="btnResetTree" onClick={() => reset()}>Reset Tree</Button>
</>
);
);

Storybook

Checkout the Storybook for interactive examples

Props

items: TreeItem[]

Required. The list of items to display in the tree.

enableSearch?: boolean

Defaults to false. When enabled, there is a search input box that will display and allow for the user to limit the items in the tree based on the typed search value.

searchLabel?: string

The label that displays above the text box.

expandAll?: boolean

Defaults to false. When true, the tree view will be entirely expanded on initial load.

displayDisabledItems?: boolean

Defaults to true. When true, disabled items will be hidden in the tree.

onItemsSelected?: (selectedIds: TreeItem[]) => void

Whenever an item is selected in the tree, it fires this event to let the parent know of the items that are selected.

onItemsExpanded?: (expandedItems: TreeItem[]) => void

Whenever an item is expanded in the tree, it fires this event.

Functions

buildTree(data: any, expandedIds: string[], selectedIds: string[])

Whenever the items are in a flat array, call this method to build the hierarchical list that is ready for the tree.

Types

TreeItem

id: string
parentId: string
isExpanded: boolean
isSelected: boolean
isHidden: boolean
isDisabled: boolean
name: string
children: TreeItem[]
areAllChildrenSelected: boolean