amay
amay

Reputation: 415

Return multiple elements from React Component

I have a component that renders a table with appropriate styling. It is, at the moment, a single monolithic component that takes a huge chunk of data defining columns and data for all the rows.

<MyTable
    columns={myColumnList}
    data={myTableData}
/>

One of the key features of this table is that it will render two rows if there is additional data not defined in the list of columns. So selecting a row will reveal additional data not displayed in the table.

I would like to break this component into smaller elements so that I can use only the bits that I need or use alternatives. Something like:

<MyTable>
<MyTableHeader columns={myColumnList} />
<MyTableBody>
    <MyTableRow data={row1Data} />
    <MyTableRow data={row2Data} />
    <MyTableRow data={row3Data} />
</MyTableBody>
<MyTableFooter />
</MyTable>

But, could produce two rows. To do this I would need a component that could potentially have to render two elements.

The normal way to return multiple elements from a component is to wrap it in a but that is invalid html within a table.

Is there any way that I can have a React Component that renders multiple elements without wrapping them a single ?

Or, is there a simpler solution that I have missed.

Upvotes: 0

Views: 1334

Answers (2)

Willy G
Willy G

Reputation: 1252

Create a function which returns the elements you need.

  const fun = (items) => items.map((item) => <tr key={item.id}>item.name</tr>);

Call it inside the table body:

<tbody>
{fun(items)}
</tbody>

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74605

A <table> can have multiple <tbody> children, so one option would be for the "row" component to return something like:

<tbody>
    <trow></trow>
    <trow></trow>
</tbody>

If you did this, you should remove the "body" component that was wrapping your rows.

Upvotes: 0

Related Questions