25
loading...
This website collects cookies to deliver better user experience
treeData
is an array of node
objects.node
object.
const treeData = [
{
key: "0",
label: "Documents",
children: [
{
key: "0-0",
label: "Document 1-1",
children: [
{
key: "0-1-1",
label: "Document-0-1.doc",
},
{
key: "0-1-2",
label: "Document-0-2.doc",
},
],
},
],
},
{
key: "1",
label: "Desktop",
children: [
{
key: "1-0",
label: "document1.doc",
},
{
key: "0-0",
label: "documennt-2.doc",
},
],
},
{
key: "2",
label: "Downloads",
children: [],
},
];
function App() {
return (
<div className="App">
<h1>React Tree View</h1>
<Tree treeData={treeData} />
</div>
);
}
Tree
component that takes the treeData
as a prop.Tree
component maps through the treeData
and returns a TreeNode
component that takes the tree node
as a prop.function Tree({ treeData }) {
return (
<ul>
{treeData.map((node) => (
<TreeNode node={node} key={node.key} />
))}
</ul>
);
}
showChildren
state is the state responsible for displaying the Tree
component.handleClick
is a click handler function that toggles the showChildren
state.TreeNode
component displays the node label
TreeNode
component also conditionally renders the Tree
component if the showChildren
state is true and passes the node children
to the Tree
component as a prop.function TreeNode({ node }) {
const { children, label } = node;
const [showChildren, setShowChildren] = useState(false);
const handleClick = () => {
setShowChildren(!showChildren);
};
return (
<>
<div onClick={handleClick} style={{ marginBottom: "10px" }}>
<span>{label}</span>
</div>
<ul style={{ paddingLeft: "10px", borderLeft: "1px solid black" }}>
{showChildren && <Tree treeData={children} />}
</ul>
</>
);
}