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

Woohoo! The React team finally added 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.


I know this has been an old post, but maybe my answer could be a help for newbies like me.

In React 16.2, improved support for Fragments was added.

You can now return it like this:

return (
  <>
    <tr><td>Item 1</td></tr>
    <tr><td>Item 2</td></tr>
  </>
);

You can wrap it with <></> or <Fragment></Fragment>.

If you would like to pass some attributes, only key is supported at the time of writing, and you'll have to use <Fragment /> since the short syntax <></> doesn't accept attributes.

Note: If you are going to use the short syntax, make sure that you are using Babel 7.

Source Reference


This is a limitation currently, but will likely be fixed at some point in the future (there's some open issues on the github repo).

For now, you can use a function which returns an array (this is basically a stateless component):

function things(arg, onWhatever){
    return [
        <tr><td>Item 1</td></tr>,
        <tr><td>Item 2</td></tr>
    ];
}

And use that in your component.

return (
    <table><tbody>
      {things(arg1, this.handleWhatever)}
      {things(arg2, this.handleWhatever)}
    </tbody></table>
);

Update

In React 16 you will be able to return an array from render.

Another Update

You can now either return a top level array, or use <React.Fragment>.

With an array we need to place a key on each item, as React doesn't know that the two elements are constant, instead of a dynamically created list:

function RowPair() {
  return [
    <tr key="first"><td>First</td></tr>,
    <tr key="second"><td>Second</td></tr>,
  ]
}

With React.Fragment, it behaves much more like wrapping it in a <div> or similar, where a key isn't required if we're not building the children dynamically. First, we can wrap the array in a Fragment:

function RowPair() {
  return <React.Fragment>{[
    <tr key="first"><td>First</td></tr>,
    <tr key="second"><td>Second</td></tr>,
  ]}</React.Fragment>
}

And then we can eliminate the array and keys entirely:

function RowPair() {
  return <React.Fragment>
    <tr><td>First</td></tr>
    <tr><td>Second</td></tr>
  </React.Fragment>
}

Tags:

Reactjs