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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

You can wrap it to the brackets like this:

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

Questions:
Answers:

This example is work well for me:

let values = [];

if (props.Values){
  values = [
    <tr key={1}>
      <td>props.Values[0].SomeValue</td>
    </tr>
  ,
    <tr key={2}>
        <td>props.Values[1].SomeValue</td>
        </tr>
    ];
}

return (
    <table className="no-border-table table">
      <tbody>
        <tr>
            <th>Some text</th>
        </tr>
        {values}
      </tbody>
    </table>
)

Questions:
Answers:

Something like this syntax worked for me

this.props.map((data,index)=>{return( [ <tr>....</tr>,<tr>....</tr>];)});