[SalesForce] how to populate lightning menu item in LWC dynamically using for:each directive

I'm trying to populate the lightning menu item in LWC with values from get method in javascript. however I'm stopped with an error

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

I'm attaching the code for reference

import { LightningElement} from 'lwc';

export default class App extends LightningElement {

    get menuItemValues(){
        [{label :'menu1',
        value : 'menu1'},
        {label :'menu2',
        value : 'menu2'},
        {label :'menu3',
        value : 'menu3'},
        {label :'menu4',
        value : 'menu4'},
        {label :'menu5',
        value : 'menu5'}]
    }
}

    <template>
<lightning-card title ="Demo on LWC" >
<div class="slds-m-top_large">
    <lightning-button-menu icon-name="utility:rows"
    alternative-text="Toggle menu">
    <template for:each={menuItemValues} for:item="menuvalue" >  
    <lightning-menu-item 
        label={menuvalue.label}
        value={menuvalue.value}
        >
    </lightning-menu-item>
    </template>
</lightning-button-menu>
</div>
</lightning-card>
</template>

Best Answer

As per the developer guide, you must include a key attribute to allow the infrastructure to target changes in the UI when reacting to changes. The key value needs to be unique in the given context. In your case you should add the key to the menu item. On the assumption the menuvalue.value is unique, it can be:

<template for:each={menuItemValues} for:item="menuvalue" >  
    <lightning-menu-item 
        label={menuvalue.label}
        value={menuvalue.value}
        key={menuvalue.value}>
    </lightning-menu-item>
</template>

I would also update the component to use the following approach:

@track
menuItemValues =
    [{label :'menu1',
    value : 'menu1'},
    {label :'menu2',
    value : 'menu2'},
    {label :'menu3',
    value : 'menu3'},
    {label :'menu4',
    value : 'menu4'},
    {label :'menu5',
    value : 'menu5'}];

Having the menu item values tracked will ensure the menu updates if you change the options.

Related Topic