Building a tree component in ReactJS
Overview
In this article, we will see how we can create a tree component in reactJS to represent hierarchical data ( Eg, folder structure ).
Demo + Source Code
Demo - react-component-depot.netlify.app/tree-stru..
Video Tutorial - youtube.com/watch?v=vAKtNV8KcWg
Source Code - github.com/codegeous/react-component-depot/..
Getting Started
This project is built using create react app and deployed in netlify. This tutorial is part of my youtube video tutorial series on building reusable components in reactJS. There might be a lot of other component libraries providing options to represent tree data, but it is always better to build our own components instead of using an external library.
Data
We need to have a defined set of JSON data format to parse and render our tree component.
The children will hold the same object data structure as its parent to any nested level you wish. Based on your project needs you can setup the icon.
Tree Component
Create a tree component that accepts this data and further loop through it recursively to display the children.
<Tree data={TreeData} />
The tree component receives this data and renders each child as a tree node as shown below.
const Tree = ({ data = [] }) => {
return (
<div className="d-tree">
<ul className="d-flex d-tree-container flex-column">
{data.map((tree) => (
<TreeNode node={tree} />
))}
</ul>
</div>
);
};
Three Node component will hold a state to decide when to render its children. The children are visible only when we click on the parent node to expose them.
const TreeNode = ({ node }) => {
const [childVisible, setChildVisiblity] = useState(false);
const hasChild = node.children ? true : false;
return (
<li className="d-tree-node border-0">
<div className="d-flex" onClick={(e) => setChildVisiblity((v) => !v)}>
{hasChild && (
<div
className={`d-inline d-tree-toggler ${
childVisible ? "active" : ""
}`}
>
<FontAwesomeIcon icon="caret-right" />
</div>
)}
<div className="col d-tree-head">
<i className={`mr-1 ${node.icon}`}> </i>
{node.label}
</div>
</div>
{hasChild && childVisible && (
<div className="d-tree-content">
<ul className="d-flex d-tree-container flex-column">
<Tree data={node.children} />
</ul>
</div>
)}
</li>
);
};
Finally, if the current tree node contains children, we will render all of them as another tree node thus recursively displaying all items in the array.