0

Is there any way to pass additional data to a button-menu onselect hander?

I have a lightning-button-menu in a loop (this is a minimal example, and not a real-world case). When a menu item is selected, then handleActionsMenuSelect is called with a single event argument. The event.detail.value is set to the value of the menu item selected, in this case either edit or delete.

But since the menu is in a loop, I also need to determine which item to edit or delete. I tried putting item.id in the menu's value, but that does not appear in the event data.

Is there any way i can also pass the associated item.id to handleActionsMenuSelect?

            <template for:each={items} for:item="item">
              <lightning-button-menu label="Actions" value={item.id} onselect={handleActionsMenuSelect}>
                <lightning-menu-item label="Edit" value="edit"></lightning-menu-item>
                <lightning-menu-item label="Delete" value="delete"></lightning-menu-item>
              </lightning-button-menu>
            </template>
1
  • Add data-id and set your id as required and in handler you can get event.target.dataset.id
    – Elijah
    Commented Jun 28, 2022 at 15:07

1 Answer 1

3

You could leverage data-* attribute: define an HTML attribute whose name must start with data- and can contain only letters, numbers, dashes, periods, colons, and underscores, i.e. data-id={item.id}.
In Javascript event.currentTarget.dataset will hold every property defined in HTML, in order to get the name of the property just remove the data- prefix and remove the dashes keeping in mind that you have to capitalize the next letter every time you remove a dash. I.E. The HTML attribute data-very-long-name="something" will become dataset.veryLongName.
So you'll find the id in event.currentTarget.dataset.id.

<template for:each={items} for:item="item">
  <lightning-button-menu label="Actions" data-id={item.id} onselect={handleActionsMenuSelect}>
    <lightning-menu-item label="Edit" value="edit"></lightning-menu-item>
    <lightning-menu-item label="Delete" value="delete"></lightning-menu-item>
  </lightning-button-menu>
</template>
handleActionsMenuSelect(event) {
    const recordId = event.currentTarget.dataset.id;
    console.log('recordId:', recordId);
}
2
  • 2
    I didnt think to add it as answer and rather added same as comment :D
    – Elijah
    Commented Jun 28, 2022 at 15:09
  • Thank you @RubenDG.
    – rwg24qqwef
    Commented Jun 29, 2022 at 10:18

You must log in to answer this question.

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