Mdd
Mdd

Reputation: 4400

React - Tree Component

I am trying to make a component in React to recursively display the names in a data tree. I am not that familiar with React and am not sure what I can do in my code to remove the error I get in the console.

The error is Uncaught SyntaxError: embedded: Adjacent JSX elements must be wrapped in an enclosing tag

Here is a jsFiddle to my code: https://jsfiddle.net/go79b0dp/ Here is my example code:

var treeObj = [
  {
    id: 1,
    name: 'Bob',
    children: [
      {
        id: 2,
        name: 'Mary',
        children: [
          {id: 4, name: 'Suzy'}
        ]
      },
      {
        id: 3,
        name: 'Phil',
        children: [
          {id: 5, name: 'Jon'},
          {id: 6, name: 'Paul'}
        ]
      }
    ]
  }
];

var TreeView = React.createClass({
  getInitialState: function() {
    return {
      people: treeObj
    };
  },

  render: function() {
    var people = this.state.people;
    var nodes = people.map((i) => <TreeNode node={i} children=   {i.children} />)

    return (
      <ul>{nodes}</ul>
    );
  }
});

var TreeNode = React.createClass({
  render: function() {
    var nodes;
    if (this.props.children) {
      nodes = this.props.children.map((i) => <TreeNode node={i} children={i.children} />);
    }          
    return (
      <li>{this.props.node.name}</li>
      <ul>{nodes}</ul>
    );
  }
});

ReactDOM.render(<TreeView />, document.getElementById('container'));

Upvotes: 0

Views: 2068

Answers (1)

Andrew Burgess
Andrew Burgess

Reputation: 1797

Your TreeNode component returns two sibling components: <li> and <ul>. Basically, you're trying to return two things from the render function, and you can't do that.

Normally, the recommended solution is to wrap them both in another element. For example:

return (<div>
  <li>{this.props.node.name}</li>
  <ul>{nodes}</ul>
</div>);

However, for the tree structure you're trying to create, it would probably be better to put the <ul> inside the <li>. That would be:

return (<li>
  {this.props.node.name}
  <ul>{nodes}</ul>
</li>);

This is how nested lists are commonly done in HTML.

Upvotes: 4

Related Questions