1

I want to do treeview rendering in React. I have TreeNode class, which does recursively renders children. So basically I want to go like this:

class TreeNode extends React.Component {
    render() {
        let nestedLevel = this.props.level || 0;
        let childNodes = this.props.node.childNodes.map(function(node, index) {
            return <TreeNode key={index} node={node} level={nestedLevel+1} />
        });
        let identationMargin={margin: (nestedLevel*16)+"px"};
        return (
            <tr className="treeview-row">
                <td><span style={identationMargin} />User {this.props.node.name}</td>
            </tr>
            {childNodes}
        );
    }
}

As you alredy see, there is an error in return, sadly I have to return only one element, like div or so. But when it comes to table jsx seems to feel pretty sick. How to get out of situation?

Here is a question about multiple tbody, but.. "how can we put a tbody into another tbody then?"

Or should I first populate array of "rows" in js, and then render them in a single return (in a second component), eg:

class TreeView render() {
   rows=[];
   for(node of allNodes)
      rows.push(<TreeNode node={node}>);
   return (
      <table>
        <tbody>
          { rows }
...

What is a typical common practice, to go with?

Josh Pittman
  • 7,024
  • 7
  • 38
  • 66
xakepp35
  • 2,878
  • 7
  • 26
  • 54

2 Answers2

1

hi why can't you wrap the two elements in a React.Fragment?? like this

class TreeNode extends React.Component {
    render() {
        let nestedLevel = this.props.level || 0;
        let childNodes = this.props.node.childNodes.map(function(node, index) {
            return <TreeNode key={index} node={node} level={nestedLevel+1} />
        });
        let identationMargin={margin: (nestedLevel*16)+"px"};
        return (
            <React.Fragment> 
                <tr className="treeview-row">
                    <td><span style={identationMargin} />User {this.props.node.name}</td>
                </tr>
                {childNodes}
            </React.Fragment>
        );
    }
}
  • Is it allowable to use it like so? I thought I only may use