Rendering table rows in React

When rendering content with JSX, you have to remember that render method can only return one root node. This makes populating table rows a little tricky. For example, the following code would be invalid:

renderRows() {
    return (
        <tr>
            <td>
                Item 3
            </td>
        </tr>
    );
}

render() {

return (
                <tr>
                    <td>
                      Item 1
                    </td>
                    <td>
                      Item 2
                    </td>
                </tr>
                {this.renderRows()}
);

This is invalid because render contains two root nodes (two tr’s). You’ll see the following error occur:

Uncaught Error: Parse Error: Line 27: Unexpected identifier

To get around this limitation, you need to wrap the content in a new root node. Typically you would use a div for this purpose, but this wouldn’t be valid HTML within a table so the only solution is to use a tbody tag like so:

renderRows() {
    return (
        <tr>
            <td>
                Item 3
            </td>
        </tr>
    );
}

render() {

return (
          <tbody>                
                <tr>
                    <td>
                      Item 1
                    </td>
                    <td>
                      Item 2
                    </td>
                </tr>
                {this.renderRows()}
          </tbody>
);

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.