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

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>
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)