I'm trying to have a component that can find parent/child components of the same type. These components will also have to be "repeatable" programmatically.
Such that:
<MyComponent id="1>
<div>
<MyComponent id="2">
<div>
<MyComponent id="3"></MyComponent>
</div>
<div>
<MyComponent id="4"></MyComponent>
</div>
</MyComponent>
</div>
</MyComponent>
Basically what I need, is a way to traverse the tree of MyComponents (traversal is logically controlled).
I can pass control/parameters to the parent component, or have the parent component pass control/parameters to children components in a predefined order (based on data). I have two methods to do this, both involve preprocessors. One is a preprocessor that generates a new Component for each MyComponent found, with some boilerplate. Something like:
var MyComponent_1 = React.createClass({
initialState: function(){ return {currentObject: 0} },
parentCallback: function(x){ /* traversal logic */ },
render: function(){
var nodes=[];
for(var i=0;i<RepeatParam;i++) nodes.push((<div><MyComponent_2 parent={parent}></MyComponent_2></div>));
return nodes;
}
});
var MyComponent_2 /** just like the above */
Another method was to add function closures, something like this:
var $parent=0, parent=0;
<div>
(function(){parent=$parent;$parent=1;
return (<MyComponent parent={parent}>
<div>
(function(){parent=$parent;$parent=2;
<MyComponent parent={parent}></MyComponent>
})()
</div></MyComponent>}))()</div>
Yet another method was to use global variables and inject them into the createClass.
All of these methods seem wrong, and as if I have a very big misunderstanding of how React should work. Is there a more elegant way to be able to traverse the tree of components, and what is the anti-pattern I am committing; how should I be doing this?