I'm doing a hierarchy tree view in React.js by recursion. I fetch categories from the DB and prepare an array in a structure that each array element is a object that has a prroperty that is an array consisting of his children:
React.js call recursive function in render
I'm already able to generate the view, but now my problem is setting the onClick={ } property for each element.
For some reason, the elements of the first level of the tree works well with the onClick function, but starting at level two, whenever I click any element, the function that is bound to the click is called two, three, four times, dependends on the current element's tree level.
MY function with the onClick:
printTree: function(level){
var self = this;
var level_length = level.length;
if(level_length >= 1){
return(
<ul>
{
level.map(function(category){
return (
<li key={category.fields.name} onClick={self.editCategory.bind(self,category)}><a>{category.fields.name}</a>
{ self.printTree(category.sons_array)}
</li>
)
})
}
</ul>
)
}
}
The input parameter level is always an array..that consists of a level of the tree,a collection of objects that will be processed this iteration.
I think that my problem is calling the function recursively passing self. In the first time that the function is called, self points to the actual this and everything works fine, but starting ata level two in the recursion, self will be pointing to the previous function in the recursive call and not to the this, but I don't know how to fix it.
category.fields.name's value always unique ?<li onClick={foo} id="foo"><ul><li onClick={foo} id="bar"></ul></li>If you click on#barin that markup,#foowill get a click event as well.onClickbound to each<a>, the situation is like I described. Click events bubble and will trigger click handlers on all ancestors as they bubble. Inside the click handler you can callevent.stopPropagationto prevent a click that you handled in a descendant from reaching an ancestor with another handler. You can also checkevent.target === event.currentTargetto see if the event originated on the current bubble target.