React component for efficiently rendering large tree structures
This package provides a lightweight and flexible solution for rendering large tree structures. It is built on top of the react-window library.
Attention! This library is entirely rewritten to work with the
react-window. If you are looking for the tree view solution for the react-virtualized, take a look at react-virtualized-tree.
NOTE: This is the documentation for version
3.x.x. For version
2.x.xsee this branch.
# npm npm i react-window react-vtreeYarn
yarn add react-window react-vtree
FixedSizeTree
You can also take a look at the very similar example at the Storybook:
import {FixedSizeTree as Tree} from 'react-vtree';// Tree component can work with any possible tree structure because it uses an // iterator function that the user provides. Structure, approach, and iterator // function below is just one of many possible variants. const treeNodes = [ { name: 'Root #1', id: 'root-1', children: [ { children: [ {id: 'child-2', name: 'Child #2'}, {id: 'child-3', name: 'Child #3'}, ], id: 'child-1', name: 'Child #1', }, { children: [{id: 'child-5', name: 'Child #5'}], id: 'child-4', name: 'Child #4', }, ], }, { name: 'Root #2', id: 'root-2', }, ];
// This helper function constructs the object that will be sent back at the step // [2] during the treeWalker function work. Except for the mandatory
data
// field you can put any additional data here. const getNodeData = (node, nestingLevel) => ({ data: { id: node.id.toString(), // mandatory isLeaf: node.children.length === 0, isOpenByDefault: true, // mandatory name: node.name, nestingLevel, }, nestingLevel, node, });// The
treeWalker
function runs only on tree re-build which is performed // whenever thetreeWalker
prop is changed. function* treeWalker() { // Step [1]: Define the root node of our tree. There can be one or // multiple nodes. for (let i = 0; i < treeNodes.length; i++) { yield getNodeData(treeNodes[i], 0); }while (true) { // Step [2]: Get the parent component back. It will be the object // the
getNodeData
function constructed, so you can read any data from it. const parent = yield;for (let i = 0; i < parent.node.children.length; i++) { // Step [3]: Yielding all the children of the provided component. Then we // will return for the step [2] with the first children. yield getNodeData(parent.node.children[i], parent.nestingLevel + 1); }
} }
// Node component receives all the data we created in the
treeWalker
+ // internal openness state (isOpen
), function to change internal openness // state (setOpen
) andstyle
parameter that should be added to the root div. const Node = ({data: {isLeaf, name}, isOpen, style, setOpen}) => ({!isLeaf && ( setOpen(!isOpen)}> {isOpen ? '-' : '+'} )});{name}ReactDOM.render( {Node} , document.querySelector('#root'), );
FixedSizeList
You can read more about these properties in the
FixedSizeListdocumentation.
children: component
className: string = ""
direction: strig = "ltr"
height: strig | number
initialScrollOffset: number = 0
innerRef: function | createRef object. This property works as it described in the
react-window. For getting a
FixedSizeListreference use
listRef.
innerElementType: React.ElementType = "div"
innerTagName: string
react-window.
itemData: any
itemKey: function
itemSize: number
layout: string = "vertical"
onItemsRendered: function
onScroll: function
outerRef: function | createRef object
outerElementType: React.ElementType = "div"
outerTagName: string
react-window.
overscanCount: number = 1
style: object = null
useIsScrolling: boolean = false
width: number | string
async: boolean
This option allows making the tree asynchronous; e.g. you will be able to load the branch data on the node opening. All it does under the hood is preserving the tree state between tree buildings on
treeWalkerupdate, so the user does not see the tree resetting to the default state when the async action is performed.
To see how it works you can check the
AsyncDatastory. You can use the
disableAsyncto see what will happen on the async action if the
asyncprop is
false.
If it is combined with the
placeholderoption, the tree re-building won't be interrupted by showing the placeholder; it will be shown only at the first time the tree is building.
To see how two options interact with each other see the
AsyncDataIdlestory.
children: component
The
Nodecomponent responsible for rendering each node.
It receives the following props:
react-window's
Rowcomponent:
style: object
isScrolling: boolean- if
useIsScrollingis enabled.
Node-specific props:
FixedSizeNodePublicStateobject.
treeData: any- any data provided via the
itemDataproperty of the
FixedSizeTreecomponent.
placeholder: ReactNode | null
This property receives any react node that will be displayed instead of a tree during the building process. This option should only be used if the tree building process requires too much time (which means you have a really giant amount of data, e.g. about a million nodes).
Setting this option enables the
requestIdleCallbackunder the hood for browsers that support this feature. For other browsers the original scenario is applied; no placeholder will be shown.
Using this feature allows avoiding UI freezes; however, it may slightly increase the time spent for the building process.
To see how it works, you can check the BigData story. Use
placeholdertool to add and remove placeholder.
If you have an asynchronous giant tree and want to use profits of
requestIdleCallbackbut don't want placeholder to be shown on the first render (that is probably quite small because all other data will be loaded asynchronously), set
placeholderto
null. No placeholder will be shown on the first render but the
requestIdleCallbackbuilding will be enabled and allow avoiding freezes on tree re-building when tree becomes bigger.
To see how it works you can check the AsyncDataIdle story. It uses the
nullplaceholder, so no text is shown for the first build but async requests don't block the UI.
buildingTaskTimeout: number
This option works in tandem with the
placeholderoption. With it, you can set the task timeout for the
requestIdleCallback. The
buildingTaskTimeoutwill be sent directly as the
requestIdleCallback's
timeoutoption.
listRef: Ref
This option allows you to get the instance of the internal
react-windowlist. It is usually unnecessary because all necessary methods are already provided but still can be useful for edge cases.
rowComponent: component
This property receives a custom
Rowcomponent for the
FixedSizeListthat will override the default one. It can be used for adding new functionality.
Rowcomponent receives the following props:
index: number
data: object- the data tree component provides to
Row. It contains the following data:
component: component- a
Nodecomponent to create a React element from.
getRecordData: function- a function that gets the record data by
index. It returns a
FixedSizeNodePublicStateobject.
treeData: any- any data provided via the
itemDataproperty of the
FixedSizeTreecomponent.
style: object
isScrolling: boolean
* treeWalker()
An iterator function that walks around the tree and yields node data to build an inner representation of the tree. For algorithm details, see TreeWalker section.
The
treeWalkerfunction should yield the object of the following shape:
data: FixedSizeNodeData- this field is mandatory. See
FixedSizeNodeDatatype for the shape.
...- you can add any other data to this object. It will be sent directly to the
treeWalkerat the step [2] of the execution.
Tree is re-computed on each
treeWalkerchange. To avoid unnecessary tree re-computation keep the
treeWalkermemoized (e.g. with
useCallbackhook). If you want to update tree data, send the new version of
treeWalkerto the tree component.
Note that when
treeWalkeris updated no internal state will be shared with the new tree. Everything will be built from scratch.
The component provides the following methods.
scrollToItem(id: string | symbol, align?: Align): void
The
scrollToItemmethod behaves the same as
scrollToItemfrom
FixedSizeListbut receives node
idinstead of
index.
async recomputeTree(state): void
This method starts the tree traversing to update the internal state of nodes.
It receives
stateobject that contains nodes'
idas keys and update rules as values. Each record traverses a subtree of the specified node (also "owner node") and does not affect other nodes (it also means that if you specify the root node the whole tree will be traversed).
The rules object has the following shape:
open: boolean- this rule changes the openness state for the owner node only (subtree nodes are not affected).
subtreeCallback(node: object, ownerNode: object): void- this callback runs against each node in the subtree of the owner node (including the owner node as well). It receives the subtree node and the owner node. Changing any property of the subtree node will affect the node state and how it will be displayed (e.g. if you change the node openness state it will be displayed according to the changed state).
The order of rules matters. If you specify the child node rules before the parent node rules, and that rules affect the same property, the parent node
subtreeCallbackwill override that property. So if you want to override parent's rules, place children rules after the parent's.
The type of the node objects received by
subtreeCallbackis
FixedSizeNodePublicState. See the types description below.
recomputeTreeexample
// The tree const tree = { name: 'Root #1', id: 'root-1', children: [ { children: [ {id: 'child-2', name: 'Child #2'}, {id: 'child-3', name: 'Child #3'}, ], id: 'child-1', name: 'Child #1', }, { children: [{id: 'child-5', name: 'Child #5'}], id: 'child-4', name: 'Child #4', }, ], };// recomputeTree
tree.recomputeTree({ 'root-1': { open: false, subtreeCallback(node, ownerNode) { // Since subtreeCallback affects the ownerNode as well, we can check if the // nodes are the same, and run the action only if they aren't if (node !== ownerNode) { // All nodes of the tree will be closed node.isOpen = false; } }, }, // But we want
child-4
to be open 'child-4': true, });
FixedSizeNodeData- value of the
datafield of the object yielded by the
treeWalkerfunction. The shape is the following:
id- a unique identifier of the node.
isOpenByDefault- a default openness state of the node.
...- you can add any number of additional fields to this object. This object without any change will be sent directly to the
Nodecomponent. You can also use
getRecordDatafunction to get this object along with the other record data by the index. To describe that data, you have to create a new type that extends the
FixedSizeNodeDatatype.
FixedSizeNodePublicState- the node state available for the
Nodecomponent and
recomputeTree's
subtreeCallbackfunction. It has the following shape:
data: FixedSizeNodeData.
isOpen: boolean- a current openness status of the node.
setOpen(state: boolean): function- a function to change the openness state of the node. It receives the new openness state as a
booleanand opens/closes the node accordingly.
FixedSizeTreeProps- props that
FixedSizeTreecomponent receives. Described in the Props section.
FixedSizeTreeState- state that
FixedSizeTreecomponent has.
VariableSizeTree
You can also take a look at the very similar example at the Storybook:
import {VariableSizeTree as Tree} from 'react-vtree';// Tree component can work with any possible tree structure because it uses an // iterator function that the user provides. Structure, approach, and iterator // function below is just one of many possible variants. const tree = { name: 'Root #1', id: 'root-1', children: [ { children: [ {id: 'child-2', name: 'Child #2'}, {id: 'child-3', name: 'Child #3'}, ], id: 'child-1', name: 'Child #1', }, { children: [{id: 'child-5', name: 'Child #5'}], id: 'child-4', name: 'Child #4', }, ], };
// This helper function constructs the object that will be sent back at the step // [2] during the treeWalker function work. Except for the mandatory
data
// field you can put any additional data here. const getNodeData = (node, nestingLevel) => ({ data: { defaultHeight: itemSize, // mandatory id: node.id.toString(), // mandatory isLeaf: node.children.length === 0, isOpenByDefault: true, // mandatory name: node.name, nestingLevel, }, nestingLevel, node, });// The
treeWalker
function runs only on tree re-build which is performed // whenever thetreeWalker
prop is changed. function* treeWalker() { // Step [1]: Define the root node of our tree. There can be yielded one or // multiple nodes. yield getNodeData(tree, 0);while (true) { // Step [2]: Get the parent component back. It will be the object // the
getNodeData
function constructed, so you can read any data from it. const parent = yield;for (let i = 0; i < parent.node.children.length; i++) { // Step [3]: Yielding all the children of the provided component. Then we // will return for the step [2] with the first children. yield getNodeData(parent.node.children[i], parent.nestingLevel + 1); }
} }
// Node component receives current node height as a prop const Node = ({data: {isLeaf, name}, height, isOpen, style, setOpen}) => (
{!isLeaf && ( setOpen(!isOpen)}> {isOpen ? '-' : '+'} )});{name}const Example = () => ( {Node} );
VariableSizeList
You can read more about these properties in the
VariableSizeListdocumentation.
Since
VariableSizeListin general inherits properties from the
FixedSizeList, everything described in the same section for
FixedSizeTreeaffects this section. For the rest, there are the following changes:
estimatedItemSize: number = 50
itemSize: (index: number) => number. This property is optional. If it is not provided, the
defaultHeightof the specific node will be used. Advanced property; prefer using node state for it.
children
The
Nodecomponent. It is the same as the
FixedSizeTree's one but receives properties from the
VariableSizeNodePublicStateobject.
listRef: Ref
listRefof
FixedSizeTree.
rowComponent: component
rowComponentin the
FixedSizeTreesection; the
getRecordDatareturns the
VirtualSizeNodePublicStateobject.
* treeWalker(refresh: boolean)
An iterator function that walks over the tree. It behaves the same as
FixedSizeTree's
treeWalker. The
dataobject should be in the
VariableSizeNodeDatashape.
The component provides the following methods:
scrollToItem(id: string | symbol, align?: Align): void
The
scrollToItemmethod behaves the same as
scrollToItemfrom
VariableSizeListbut receives node
idinstead of
index.
resetAfterId(id: string | symbol, shouldForceUpdate: boolean = false): void
This method replaces the
resetAfterIndexmethod of
VariableSizeListbut works exactly the same. It receives node
idas a first argument.
async recomputeTree(state): void
See
FixedSizeTree's
recomputeTreedescription. There are no differences.
All types in this section are the extended variants of
FixedSizeTreetypes.
VariableSizeNodeData- this object extends
FixedSizeNodeDataand contains the following additional fields:
defaultHeight: number- the default height the node will have.
VariableSizeNodePublicState. The node state object. Extends the
FixedSizeNodePublicStateand contains the following additional fields:
height: number- the current height of the node. The node will be displayed with this height.
resize(newHeight: number, shouldForceUpdate?: boolean): function- a function to change the height of the node. It receives two parameters:
newHeight: number- a new height of the node.
shouldForceUpdate: boolean- an optional argument that will be sent directly to the
resetAfterIndexmethod.
VariableSizeTreeProps.
VariableSizeTreeState.
The
treeWalkeralgorithm works in the following way. During the execution, the
treeWalkerfunction sends a bunch of objects to the tree component which builds an internal representation of the tree. However, for it, the specific order of yieldings should be performed.
undefined. In exchange, you will receive a node for which you should yield all the children in the same way you've done with the root ones.
undefinedagain and in exchange receive the next node. It may be:
treeWalker's loop manually.
The example of this algorithm is the following
treeWalkerfunction:
function* treeWalker() { // Here we start our tree by yielding the data for the root node. yield getNodeData(rootNode, 0);while (true) { // Here in the loop we receive the next node whose children should be // yielded next. const parent = yield;
for (let i = 0; i < parent.node.children.length; i++) { // Here we go through the parent's children and yield them to the tree // component yield getNodeData(parent.node.children[i], parent.nestingLevel + 1); // Then the loop iteration is over, and we are going to our next parent // node. }
} }
2.x.x->
3.x.x
If you use
react-vtreeof version 2, it is preferable migrate to the version 3. The third version is quite different under the hood and provides way more optimized approach to the initial tree building and tree openness state change. The most obvious it becomes if you have a giant tree (with about 1 million of nodes).
To migrate to the new version, you have to do the following steps.
treeWalker
The
treeWalkerwas and is the heart of the
react-vtree. However, now it looks a bit different.
Old
treeWalkerworked for both initial tree building and changing node openness state:
function* treeWalker(refresh) { const stack = [];stack.push({ nestingLevel: 0, node: rootNode, });
// Go through all the nodes adding children to the stack and removing them // when they are processed. while (stack.length !== 0) { const {node, nestingLevel} = stack.pop(); const id = node.id.toString();
// Receive the openness state of the node we are working with const isOpened = yield refresh ? { id, isLeaf: node.children.length === 0, isOpenByDefault: true, name: node.name, nestingLevel, } : id; if (node.children.length !== 0 && isOpened) { for (let i = node.children.length - 1; i >= 0; i--) { stack.push({ nestingLevel: nestingLevel + 1, node: node.children[i], }); } }
} }
The new
treeWalkeris only for the tree building. The
Treecomponent builds and preserves the tree structure internally. See the full description above.
// This function prepares an object for yielding. We can yield an object // that has `data` object with `id` and `isOpenByDefault` fields. // We can also add any other data here. const getNodeData = (node, nestingLevel) => ({ data: { id: node.id.toString(), isLeaf: node.children.length === 0, isOpenByDefault: true, name: node.name, nestingLevel, }, nestingLevel, node, });function* treeWalker() { // Here we send root nodes to the component. for (let i = 0; i < rootNodes.length; i++) { yield getNodeData(rootNodes[i], 0); }
while (true) { // Here we receive an object we created via getNodeData function // and yielded before. All we need here is to describe its children // in the same way we described the root nodes. const parentMeta = yield;
for (let i = 0; i < parentMeta.node.children.length; i++) { yield getNodeData( parentMeta.node.children[i], parentMeta.nestingLevel + 1, ); }
} }
Components haven't been changed a lot but you may want to add new features like:
recomputeTreemethod
The
recomputeTreemethod now receives a list of nodes to change (previously, it was an
opennessStateobject). See the full description above.
The most important change is the introduction of the
subtreeCallback. It is a function that will be applied to each node in the subtree of the specified node. Among other useful things it also allows imitating the behavior of old
useDefaultOpennessand
useDefaultHeightoptions.
Old
recomputeTree:
treeInstance.recomputeTree({ opennessState: { 'node-1': true, 'node-2': true, 'node-3': false, }, refreshNodes: true, useDefaultOpenness: false, });
New
recomputeTree:
treeInstance.recomputeTree({ 'node-1': true, 'node-2': { open: true, subtreeCallback(node, ownerNode) { if (node !== ownerNode) { node.isOpen = false; } }, }, 'node-3': false, });
toggle()calls to
setOpen(boolean)
In the
3.x.xversion node provides a
setOpenfunction instead of
togglethat allows more fine-grained control over the openness state.
Old
toggle:
const Node = ({data: {isLeaf, name}, isOpen, style, toggle}) => ({!isLeaf && ();{isOpen ? '-' : '+'})}{name}
New
setOpen:
javascript const Node = ({data: {isLeaf, name}, isOpen, style, setOpen}) => ({!isLeaf && ();// Imitating the old `toggle` function behavior setOpen(!isOpen)}>{isOpen ? '-' : '+'})}{name}
Using node IDs as keys should improve React rendering performance. However, it means that you won't be able to use
Symbolas IDs anymore. You should move all your IDs to be strings instead of symbols.