Reputation: 27
I would like to generate TreeNode like below in React.
<TreeNode>
<TreeNode>
<TreeNode>
</TreeNode>
</TreeNode>
</TreeNode>
Below is the code i tried
const numberVal = [1,2,3];
function renderPage(){
return(numberVal.map((n, i) => (
<TreeNode></TreeNode>
)));
}
It is displaying like below:
<TreeNode></TreeNode>
<TreeNode></TreeNode>
<TreeNode></TreeNode>
Could anyone let me know the way in which can do?
Upvotes: 0
Views: 193
Reputation: 1249
I would use recursion:
const numberVal = [1,2,3];
function renderPage(){
const processData = array => {
if(array.length) {
const [first, ...rest] = array || [];
return (
<TreeNode>
{processData(rest)}
</TreeNode>
)
}
return null;
}
return processData(numberVal);
}
Upvotes: 2
Reputation: 5581
Try something like this. While building a node, include the children structure and let it include them inside if present
const makeNodes([nodeId, ...children]) {
return (
<TreeNode id={nodeId}>
{ children ? makeNodes(children) : null }
</TreeNode>
);
}
render() {
const a = [1,2,3];
return makeNodes(a);
}
This way you can make even more complex structures like this:
render() {
const a = [ [1,2,3], [4], [5,6] ];
return (
<div>
{ a.map(nodes => makeNodes(nodes)) }
</div>
);
}
and it should produce
<TreeNode id=1>
<TreeNode id=2>
<TreeNode id=3>
</TreeNode>
</TreeNode>
</TreeNode>
<TreeNode id=4>
</TreeNode>
<TreeNode id=5>
<TreeNode id=6>
</TreeNode>
</TreeNode>
Note that this code wasn't actually run and might have syntax errors - consider it pseudo-code.
Upvotes: 0