Recently I am trying to solve a problem where I have to render a document tree menu (hierarchical) from a nested JSON coming from a request call.
Say my JSON looks like this
[{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, {
"title": "Cloths",
"path": "/root",
"children": [{
"title": "T shirt",
"path": "/root/Cloths",
"children": []
}, {
"title": "Shirt",
"path": "/root/Cloths",
"children": []
}]
}]
I have to create the following DOM from the above JSON
SOLVED through jQuery:
I have the function ready to convert the JSON to DOM: in normal jQuery I would do something like the following:
$(function(){
function get_tree(tree_data){
dom += '<ul>';
for(var i in tree_data){
if(tree_data[i].children.length > 0){
dom += '<li>';
dom += '<a href="#" class="tree-parent-anchor">'+tree_data[i].title+'</a>';
get_tree(tree_data[i].children);
dom += '<li>';
}
else{
dom += '<li>'+tree_data[i].title+'</li>'
}
}
dom+= '</ul>'
}
var tree_data = JSON.parse($('pre').text());
var dom= '<ul id="Menu-list">';
get_tree(tree_data);
dom+= '</ul>'
$('div').append(dom);
})
In REACT.JS I tried this (ofcrse it doesn't works):
export default class DocTree extends Component{
state = {treeData: [{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, ...
}]
}
render(){
const tree_data = this.state.treeData;
function get_tree(tree_data, dom){
<ul>
for(var i in tree_data)
if(tree_data[i].children.length > 0)
<li>
<a href="#" className="tree-parent-anchor">{tree_data[i].title}</a>
get_tree(tree_data[i].children);
<li>
else
<li>{tree_data[i].title}</li>
</ul>
var dom = <ul id="Menu-list">
get_tree(tree_data);
</ul>
return(
<div>
{dom}
</div>
);
}
}
I dont exactly how to achieve the same through React.js syntax
Please help me with - How do it in React.js (am using React.js 16.2.0)
