Basic with controlled expandable node
This example demonstrates how to create a simple tree with controlled expandable node
- Drinks-7
- Vegetables-16
import React, { useState } from "react";
import { IoMdArrowDropright } from "react-icons/io";
import TreeView, { flattenTree } from "react-accessible-treeview";
import cx from "classnames";
const folder = {
name: "",
children: [
{
name: "Fruits",
children: [
{ name: "Avocados" },
{ name: "Bananas" },
{ name: "Berries" },
{ name: "Oranges" },
{ name: "Pears" },
],
},
{
name: "Drinks",
children: [
{ name: "Apple Juice" },
{ name: "Chocolate" },
{ name: "Coffee" },
{
name: "Tea",
children: [
{ name: "Black Tea" },
{ name: "Green Tea" },
{ name: "Red Tea" },
{ name: "Matcha" },
],
},
],
},
{
name: "Vegetables",
children: [
{ name: "Beets" },
{ name: "Carrots" },
{ name: "Celery" },
{ name: "Lettuce" },
{ name: "Onions" },
],
},
],
};
const data = flattenTree(folder);
function ControlledExpandedNode() {
const [expandedIds, setExpandedIds] = useState();
const onKeyDown = (e) => {
if (e.key === "Enter") {
getAndSetIds();
}
};
const getAndSetIds = () => {
setExpandedIds(
document
.querySelector("#txtIdsToExpand")
.value.split(",")
.filter(val => !!val.trim())
.map((x) => {
if (isNaN(parseInt(x.trim()))) {
return x;
}
return parseInt(x.trim());
})
);
};
return (
<div>
<div>
<label htmlFor="txtIdsToExpand">
Comma-delimited list of branch node IDs to expand:
</label>
<input id="txtIdsToExpand" type="text" onKeyDown={onKeyDown} />
<button onClick={() => getAndSetIds()}>Set</button>
</div>
<div>
<button onClick={() => setExpandedIds([])}>
Clear all expanded nodes
</button>
</div>
<div className="checkbox">
<TreeView
data={data}
aria-label="Controlled expanded node tree"
expandedIds={expandedIds}
defaultExpandedIds={[1]}
nodeRenderer={({
element,
isBranch,
isExpanded,
isDisabled,
getNodeProps,
level,
handleExpand,
}) => {
return (
<div
{...getNodeProps({ onClick: handleExpand })}
style={{
marginLeft: 40 * (level - 1),
opacity: isDisabled ? 0.5 : 1,
}}
>
{isBranch && <ArrowIcon isOpen={isExpanded} />}
<span className="name">
{element.name}-{element.id}
</span>
</div>
);
}}
/>
</div>
</div>
);
}
const ArrowIcon = ({ isOpen, className }) => {
const baseClass = "arrow";
const classes = cx(
baseClass,
{ [`${baseClass}--closed`]: !isOpen },
{ [`${baseClass}--open`]: isOpen },
className
);
return <IoMdArrowDropright className={classes} />;
};
export default ControlledExpandedNode;
.basic.tree {
list-style: none;
margin: 0;
padding: 20px;
}
.basic .tree-node,
.basic .tree-node-group {
list-style: none;
margin: 0;
padding: 0;
}
.basic .tree-branch-wrapper,
.basic .tree-node__leaf {
outline: none;
}
.basic .tree-node--focused {
outline-color: rgb(77, 144, 254);
outline-style: auto;
outline-width: 2px;
display: block;
}
.basic .tree-node__branch {
display: block;
}
.basic .tree-node {
cursor: pointer;
}