thealexbaron thealexbaron - 26 days ago 11
React JSX Question

How do I render sibling elements without wrapping them in a parent tag?

In most cases, having a parent tag isn't an issue.

React.createClass({
render: function() {
return (
<tbody>
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
</tbody>
);
}
});


But there are some cases where it makes sense to have sibling elements in one render function without a parent, and especially in the case of a table, you don't want to wrap a table row in a
div
.

React.createClass({
render: function() {
return (
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
);
}
});


The second example gives the following error:
Adjacent XJS elements must be wrapped in an enclosing tag while parsing file
.

How can I render two sibling elements without wrapping them in a
<div>
or something similar?

Answer Source

Woohoo! The React team finally addressed this feature. As of React v16.0, you can do:

render() {
  // No need to wrap list items in an extra element!
  return [
    // Don't forget the keys :)
      <tr key="a"><td>Item 1</td></tr>,
      <tr key="b"><td>Item 2</td></tr>
  ];
}

See the full blog post explaining "New render return types: fragments and strings" here.