0

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>

2
  • I'm not sure where can I add the Key attribute
    – prasanth
    Commented Jun 17, 2020 at 7:34
  • Simply add the "key" attribute on the menu item, probably set using key={menuvalue.value} to ensure there's a unique value for it.
    – Phil W
    Commented Jun 17, 2020 at 7:37

2 Answers 2

3

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.

2
1

You are just missing the return keyword in your JS method.

get menuItemValues(){
    return [{label :'menu1',
    value : 'menu1'},
    {label :'menu2',
    value : 'menu2'},
    {label :'menu3',
    value : 'menu3'},
    {label :'menu4',
    value : 'menu4'},
    {label :'menu5',
    value : 'menu5'}]
}
1
  • 1
    thanks that was the change I'm required to make the code work
    – prasanth
    Commented Jun 17, 2020 at 7:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .