1

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

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>
5
  • Simple as that eh? From the documentation I thought that the key needed to uniquely identify the parent element. Guess not. – bpilling Sep 10 '20 at 2:07
  • its needed but as they are in same iteration it doesn't give an error.. – Rahul Gawale Sep 10 '20 at 3:46
  • Okay, so now that I have developed things a bit further, I get an error in teh console, and the behaviour no longer works as expected - when the fetching from server happens and re-rendering occurs. – bpilling Sep 10 '20 at 14:17
  • what error you are getting? @bpilling – Rahul Gawale Sep 10 '20 at 14:49
  • 1
    Okay, so I tried your second suggestion, and generated a new unique key that i use (simply incrementing a property in my javascript file every time it is used) - and that worked a treat. So in summary, I couldn't use the same key for both, but I could use an actual unique one. Thanks Rahul! – bpilling Sep 10 '20 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.