I'm trying to build a Tree Table that is capable of shown/hide their TR childs when clicked (among other things).
I've grab some code from the web to generate easily generate a tree structure. The problem comes trying to set a parent/child relationship with this event. I'm really not used to react so it is hard for me to understand certain things.
This is the data structure:
var data = [
{
id: 1,
label: 'Order 1',
deep: 0,
children: [{
id: 11,
label: 'Cycle November',
deep: 1,
},
{
id: 12,
label: 'Cycle December',
deep: 1,
}]
},
{
id: 2,
label: 'Order 2',
deep: 0,
children: [{
id: 21,
label: 'Cycle January',
deep: 1
}]
},
];
Then i want to click on Parent id 1 and see who their children are.
This is the code that draws the Table:
var TR = React.createClass({
childs: [],
hasParent: function() {
if (this.props.parent) {
return true;
}
else {
return false;
}
},
componentDidMount: function(){
if (this.hasParent()) {
parentKey = this.props.parent.props.keyId.split('-')[1];
thisKey = this.props.keyId.split('-')[0];
if (parentKey == thisKey) {
console.log('I set the child');
this.props.parent.props.childs.push(this);
}
}
},
handleClick: function(event) {
if (this.hasParent()) {
parent = this.props.parent;
console.log('My father is: '+parent.props.keyId);
console.log('Me and my brothers are: ');
parent.props.childs.map(function(child) {
console.log(child.props.keyId);
});
}
else {
console.log('I am: '+this.props.keyId);
console.log('My children are:');
this.props.childs.map(function(child) {
console.log(child.props.keyId);
});
}
},
isShown: function() {
return false;
},
getDefaultProps: function() {
return {
childs: new Array(),
};
},
render: function() {
var iparent = this.props.data.deep*20;
return (
<tr>
<td style={{paddingLeft: iparent+'px'}}>
<span onClick={this.handleClick} >
+ </span>
{this.props.data.label}
</td>
</tr>
);
}
});
var Tree = React.createClass({
render: function() {
var treeItems = [];
parent = null;
var renderTreeItems = function(items, parent) {
if (!items) {
return;
}
for (var i = 0; i < items.length; i++) {
if (items[i].deep == 0) {
var parent_id = items[i].deep;
}
else {
var parent_id = parent.props.data.id;
}
var key = parent_id+'-'+items[i].id;
tr = (
<TR key={key} keyId={key} data={items[i]} parent={parent} >
</TR>
);
treeItems.push(
tr
);
renderTreeItems(items[i].children, tr);
}
};
renderTreeItems(this.props.data);
return (
<table>
{ treeItems }
</table>
);
}
});
And last the HTML to attach the component:
<html>
<body>
<div id="tree"></div>
<script type="text/jsx">
React.render(<Tree data={data}/>, document.body);
</script>
</body>
</html>
The actual problem is that childs (badly written i know...) seems to be shared between all TR instances. Can someone point what i'm doing wrong and what is the best approach to deal with this? Simply: i want to hide/show childs clicking on the TR-First TD that "acts" as a parent.
Here is the jsfiddle http://jsfiddle.net/69z2wepo/2731/