I am trying to recursively draw a tree based on a dataset. Each level 0 item is added a class category
(which has bold text styling) , each level 1 is added group
and level 2 is added leaf
. This tree can be drawn up to two levels. But when I am recursively drawing the tree, all the levels get bold styling and mouse hover as well is applying to whole instead of each level.
Here is the sandbox that shows both the trees , one drawn using recursion other one is hardcoded using css: https://codesandbox.io/s/tree-compared-9s828h
Can someone tell me what is wrong in the recursive approach.
import React from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const DrawnTree = ({ treeData }) => {
const renderNode = (node, level) => {
const hasChildren = node.categories && node.categories.length > 0;
const isLeaf = !hasChildren;
let categoryType = "";
if (level === 0) {
categoryType = "category";
} else if (!hasChildren) {
categoryType = "leaf";
} else {
categoryType = "group";
}
const onClickNode = () => {
// Handle node click here
};
return (
<div
className={`list-row level-${level} ${categoryType}`}
onClick={onClickNode}
key={`${node.key}`}
>
<div className="list-item-holder">
{hasChildren && (
<div className="list-item-expander-holder">
<span
className={`expand-collapse-icon ${isLeaf ? "" : "expand"}`}
>
<span className="collapse-icon">
<FontAwesomeIcon icon="caret-down" />
</span>
<span className="expand-icon">
<FontAwesomeIcon icon="caret-right" />
</span>
</span>
</div>
)}
<div className="list-item-details-holder">{node.name}</div>
</div>
{hasChildren && (
<div className="list-row-children">
{node.categories.map((category) => renderNode(category, level + 1))}
</div>
)}
</div>
);
};
const renderTree = () => {
return treeData.map((node) => {
return renderNode(node, 0);
});
};
return (
<div className="tree-list-section">
<div className="left-holder-bottom-list-section">{renderTree()}</div>
</div>
);
};
export default DrawnTree;