I am making a treeview from JSON using react. So far I have made a collapsible tree using this example data:
JavaScript
x
14
14
1
var data = {
2
title: "Node 1",
3
childNodes: [
4
{title: "Childnode 1.1"},
5
{title: "Childnode 1.2",
6
childNodes: [
7
{title: "Childnode 1.2.1",
8
childNodes: [
9
{title: "Childnode 1.2.1.1"}
10
]}, {title: "Childnode 1.2.2"}
11
]}
12
]
13
};
14
But this is one object. I want to get JSON array of objects as input and generate treeview from that but I am unable to understand where to change the code.
Here’s my render function:
JavaScript
1
23
23
1
render() {
2
var childNodes;
3
4
if (this.props.node.childNodes != null) {
5
childNodes = this.props.node.childNodes.map(function (node, index) {
6
return <li key={index}><Treeview node={node}/></li>
7
});
8
}
9
10
return (
11
<form>
12
<div>
13
<input type="checkbox"/>
14
<label for>{this.props.node.title}</label>
15
</div>
16
<ul>
17
{childNodes}
18
</ul>
19
</form>
20
21
);
22
}
23
How can I change the code to work with the whole array and not just one object?
Advertisement
Answer
Recursion is fun!
JavaScript
1
35
35
1
const data = [{
2
title: "Node 1",
3
childNodes: [
4
{ title: "Childnode 1.1" },
5
{
6
title: "Childnode 1.2",
7
childNodes: [
8
{
9
title: "Childnode 1.2.1",
10
childNodes: [
11
{ title: "Childnode 1.2.1.1" }
12
]
13
}, { title: "Childnode 1.2.2" }
14
]
15
}
16
]
17
}];
18
19
const App = () => (
20
<form>
21
<Tree data={data} />
22
</form>
23
);
24
25
const Tree = ({data}) => (
26
<ul>
27
{data && data.map(item => (
28
<li>
29
{item.title}
30
{item.childNodes && <Tree data={item.childNodes} />}
31
</li>
32
))}
33
</ul>
34
);
35