I am trying to have a component that can find parent / child components of the same type. These components must also be “reproducible” programmatically.
In this way:
<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 cross the MyComponents tree (the traversal is logically controlled).
I can pass control / parameters to the parent component or pass the control of the parent component / parameters to the child components in a predetermined order (based on data). I have two ways to do this, both include preprocessors. One of them is a preprocessor that generates a new component for each MyComponent found with some template. Sort of:
var MyComponent_1 = React.createClass({ initialState: function(){ return {currentObject: 0} }, parentCallback: function(x){ }, 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
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>
Another method is to use global variables and paste them into createClass.
All of these methods seem to be wrong, and as if I had a very big misunderstanding of how React should work. Is there a more elegant way to be able to cross the component tree, and what is the anti-pattern that I commit; how should i do this?
source share