Skip to content

API

Exported

The exported variables, methods, and Typescript types.

Typescript types:

  • Id: node id, parent id. Type: string | number.
  • Stat: Node information.
  • HeTreeProps: Options for useHeTree.

useHeTree

ts
import { useHeTree } from "he-tree-react";
const {/* return */} = useHeTree({/* options */}) // prettier-ignore

The main function of this library. React hook. The arguments are as follows:

  • options: Options, type is object. The following are some properties in options:

    NameTypeDefaultDescription
    dataArrayData. Check Data Types.
    dataType'flat', 'tree''flat'Data Types
    idKeystring'id'key of id 名.
    parentIdKeystring'parent_id'key of the parent id. For flat data only.
    childrenKeystring'children'key of children nodes. For tree data only.
    indentnumber20Node indentation, unit is px.
    dragOpenbooleanfalseWhether to enable the function "Open node when dragging over node".
    dragOpenDelaynumber600The waiting time to open the node when dragging over the node. The unit is milliseconds.
    onDragOpenfunction(stat): voidThe callback of "Open node when dragging over node".
    direction'lrt', 'rtl''ltr'Display direction, ltr is displayed from left to right, rtl is the opposite.
    rootIdstring, nullnullThe parent id of a node that has not parent in flat data.
    virtualbooleanfalseWhether to enable virtualization. Used to improve performance when there is a lot of data.
    keepPlaceholderbooleanfalseWhether to retain placeholder when dragging out of the tree. It is recommended to enable this only on one tree page.
    openIdsArrayAll open nodes' id.
    checkedIdsArrayAll checked nodes' id.
    isFunctionReactivebooleanfalseWhether to listen for change of the callback functions. Reference

    The remaining callback functions in options:

    NameTypeDescription
    renderNode(stat)=> ReactNodeNode render.
    renderNodeBox({stat, attrs, isPlaceholder})=> ReactNodenodeBox's render. Reference.
    onChange(newData)=>voidCallback on data change
    canDrag(stat)=>boolean, null, undefined, voidWhether a node draggable. Returning null, undefined, void means inheriting the parent node.
    canDrop(stat, index)=>boolean, null, undefined, voidWhether a node droppable. Returning null, undefined, void means inheriting the parent node. The parameter index may be empty. If it is not empty, it indicates the position.
    customDragImage(event, stat)=> voidCalled event.dataTransfer.setDragImage to custom drag image. Reference.
    onDragStart(event, stat)=> void
    onExternalDragOver(event)=>booleanCalled when drag from external. Must return a Boolean value to indicate whether to handle this drag.
    onDragOver(event, stat, isExternal)=> voidisExternal indicates whether the drag is from outside.
    onDragEnd(event, stat, isOutside)=>voidCalled on dragend and this drag is started in this tree. stat is the stat of the dragged node. isOutside indicates whether it ended outside the tree.
    onExternalDrop(event, parentStat, index)=>voidCalled when the external drag ends on this tree. parentStat is the stat of the target parent node, and when it is empty, it represents the root of the tree. Index is the target position, the index of the node among siblings.

Return of useHeTree

The return of useHeTree is an object, including some states and methods. Note, this object will change every time. Do not rely on this object, but you can rely on the properties of this object. The properties are as follows:

NameTypeDescription
renderTree(options?: { className?: string, style?: React.CSSProperties }): ReactNodeTree render. Options can be passed in className and style to control the style of the root element.
getStat(idOrNodeOrStat)=>statGet stat by id, or node data, or stat object.
allIdsArrayThe ids of all nodes.
rootIdsArrayThe ids of all root nodes
rootNodesArrayAll root nodes. In tree data, it is same with options.data.
rootStatsArrayAll root nodes' stat.
placeholder{parentStat, index, level}Drag placeholder info. Null if it does not exist.
draggingStatstatWhen a drag is initiated from this tree, the stat of the dragged node. Null if it does not exist.
dragOverStatstatDragging over node's stat. May be null.
visibleIdsArrayAll visible nodes' id.
attrsListArrayAll visible nodes' attrs.
virtualListRefrefref of virtual list component, Check virtual list.
scrollToNode(idOrNodeOrStat)=>booleanScroll to node. The argument can be id, node or stat. If node not found or invisible, it return false. Example

walkTreeDataGenerator

The method of traversing tree data through for of. Executing skipChildren() in the loop will skip all child nodes of the node, and executing exitWalk will end the traversal.

ts
for (const [
  node,
  { parent, parents, siblings, index, skipChildren, exitWalk },
] of walkTreeDataGenerator(data, "children")) {
  // ...
}

walkTreeData

The method to traverse tree data through the callback method. Executing skipChildren() in the callback method will skip all child nodes of the node, and executing exitWalk will end the traversal.

ts
walkTreeDataGenerator(
  data,
  (node, { parent, parents, siblings, index, skipChildren, exitWalk }) => {
    // ...
  },
  "children"
);

findTreeData

Like Array.prototype.find. Returns the first node found. Executing skipChildren() in the callback method will skip all child nodes of the node, and executing exitWalk will end the traversal.

ts
let foundNode = findTreeData(
  data,
  (node, { parent, parents, siblings, index, skipChildren, exitWalk }) => {
    // return node.id === 1;
  },
  "children"
);

filterTreeData

Like Array.prototype.filter. Returns all nodes found. Executing skipChildren() in the callback method will skip all child nodes of the node, and executing exitWalk will end the traversal.

ts
let nodes = filterTreeData(
  data,
  (node, { parent, parents, siblings, index, skipChildren, exitWalk }) => {
    // return node.id > 1;
  },
  "children"
);

openParentsInTreeData

Open all parent nodes of a single or multiple nodes to make the node visible. Reference.

(
  treeData,
  openIds: Id[],
  idOrIds: Id | Id[],
  options?: {idKey: string, childrenKey: string}
): newOpenIds

updateCheckedInTreeData

Update the checked status of a single node or multiple nodes. This will update both their children and parents. Reference.

(
  treeData,
  checkedIds: Id[],
  idOrIds: Id | Id[],
  checked: boolean,
  options?: {idKey: string, childrenKey: string}
): [newCheckedIds, newSemiCheckedIds]

sortFlatData

Sort the flat data according to the order of the nodes in the tree. Return the new sorted array. Your data should use it to ensure order after initialized.

(
  flatData,
  options?: {idKey: string, parentIdKey: string}
): sortedData

walkFlatDataGenerator

The method of traversing flat data through for of. Executing skipChildren() in the loop will skip all the child nodes of the node, and executing exitWalk will end the traversal. Make sure the order of your data is correct before using it.

Compared to walkTreeDataGenerator, it lacks siblings, but has treeIndex, id, pid. treeIndex is the index of the node in the tree.

ts
for (const [
  node,
  { parent, parents, index, treeIndex, id, pid, skipChildren, exitWalk },
] of walkFlatDataGenerator(flatData, {
  idKey: "id",
  parentIdKey: "parent_id",
})) {
  // ...
}

walkFlatData

The method of traversing flat data through the callback method. Executing skipChildren() in the callback method will skip all child nodes of the node, and executing exitWalk will end the traversal. Before using, make sure that the order of your data is correct.

ts
walkFlatData(
  flatData,
  (
    node,
    { parent, parents, index, treeIndex, id, pid, skipChildren, exitWalk }
  ) => {
    // ...
  },
  {
    idKey: "id",
    parentIdKey: "parent_id",
  }
);

openParentsInFlatData

Open all parent nodes of a single or multiple nodes to make the node visible. Make sure your data is in the correct order before using it. Reference.

(
  flatData,
  openIds: Id[],
  idOrIds: Id | Id[],
  options?: {
    idKey: "id",
    parentIdKey: "parent_id",
  }
): newOpenIds

updateCheckedInFlatData

Update the checked status of a single node or multiple nodes. This will update both their children and parents. Make sure your data is in the correct order before using it. Reference.

(
  flatData,
  checkedIds: Id[],
  idOrIds: Id | Id[],
  checked: boolean,
  options?: {
    idKey: "id",
    parentIdKey: "parent_id",
  }
): [newCheckedIds, newSemiCheckedIds]

convertIndexToTreeIndexInFlatData

Calculate the index of a node in the tree through its parent node id and its index in the sibling nodes.

(
  flatData,
  parentId: Id | null,
  indexInSiblings: Id | null,
  options?: {
    idKey: "id",
    parentIdKey: "parent_id",
  }
): treeIndex

addToFlatData

Add a node to the flat data. It will change the original data array. Therefore, it is recommended to pass in a copy of the original data, or use it together with useImmer. Reference

(
  flatData,
  newNode,
  index: Id | null,
  options?: {
    idKey: "id",
    parentIdKey: "parent_id",
  }
):void

removeByIdInFlatData

Remove node by id from the flat data. It will change the original data array. Therefore, it is recommended to pass in a copy of the original data, or use it together with useImmer. Reference

(
  flatData,
  removeId: Id | null,
  options?: {
    idKey: "id",
    parentIdKey: "parent_id",
  }
): removedData

walkParentsGenerator

A method to iterate over another special kind of data. This data is like HTMLElement, which contains keys pointing to the parent node like parentElement.

(
  node,
  parentKeyOrGetter: string | ((node) => parent | undefined),
  options?: {
    withSelf: boolean;
  }
): Generator

parentKeyOrGetter can be a string or a method that returns the parent. options.withSelf indicates whether to include the node self. Returns Generator. Here is an example of traversing HTMLElement:

ts
let el = document.querySelector("div");
for (const parent of walkParentsGenerator(el, "parentElement", {
  withSelf: true,
})) {
  // ...
}

Stat

stat contains information related to the node. Read-only. The properties are as follows:

NameTypeDescription
_isStatbooleanIndicates whether it is a stat object
nodeobjectnode data
idIdid
pidId, nullparent id
parentobject, nullparent data
parentStatstat, nullparent stat
childIdsId[]
childrenobject[]
childStatsstat[]stats of children
siblingIdsId[]
siblingsobject[]sibling nodes
siblingStatsstat[]stats of siblings
indexnumbernode's index in siblings
levelnumbernode's depth in tree. Start from 1
openboolean
checkedboolean
draggableboolean

Last updated: