[SalesForce] LWC – Multiple table rows for each iteration in for:each – where do I put the key

I am converting an Aura component to LWC, and have hit one issue. In the Aura component two table rows are created for each iteration. However, in the LWC, I cannot create two rows for each iteration, as I need ot set a key on a single parent node. I cannot figure out how to create two rows in each iteration.

I thought about surrounding the two tr tags with another tag, but the Mozilla Developer Documentation is pretty clear that the standard defines only the following parents are allowed for tr:

<table> (only if the table has no child <tbody>
element, and even then only after any <caption>, <colgroup>, and
<thead> elements); otherwise, the parent must be <thead>, <tbody> or
<tfoot>
Mozilla Developer Network

So, in short – how can I iterate over an array, and generate two table rows for each iteration, something like so? Where would I put the key? Is this possible?

<template for:each={items} for:item="item">
    <tr><td>First row</td></tr>
    <tr><td>Second row</td></tr>
</template>

Best Answer

Yes, it is possible. You can use the same key for both of the rows.

<template for:each={items} for:item="item">
    <tr key={item.id}>
        <td>First row</td>
    </tr>
    <tr key={item.id}>
        <td>Second row</td>
    </tr>
</template>

Or you can create a unique key for each of the rows. Let's say firstRowId, secondRowId. Which you can assign to item.id + "0" and item.id + "1"

<template for:each={items} for:item="item">
    <tr key={item.firstRowId}>
        <td>First row</td>
    </tr>
    <tr key={item.secondRowId}>
        <td>Second row</td>
    </tr>
</template>