[SalesForce] How to create select option in LWC

I am creating a select option in LWC. From server side controller I am returning list of wrapper having key and value as below-

[{"key":"All Accounts","value":"00B7F000006l0B3UAI"}]

I the html file I am creating options using iteration as below. –

<select class="slds-select" id="select-01">
     <template for:each = {listViews} for:item="listViewItem">
        <option value={listViewItem.key}>{listViewItem.value}</option>
     </template>
</select>

Although, I am able to display data on the markup but But I am getting compilation error when I use it with the select option-

Missing key for element inside of iterator. Elements within iterators must have a unique, computed key value.

Any help would be appreciated

Best Answer

Whenever you use for:each you have to use key attribute in the child markup. If not it gives a compilation error.

From SF Docs:

Note that you must use a key to assign a unique value to each item in the list.

<select class="slds-select" id="select-01">
     <template for:each = {listViews} for:item="listViewItem">
        <option key={listViewItem.key} value={listViewItem.key}>{listViewItem.value}</option>
     </template>
</select>