Search code examples
reactjstypescriptmaterial-uimenu

How to get a specific ListItem from Menu Component in MUI for React


I have a List that has several ListItems which I get from an array, let's call it myCollection. Each ListItem has a MenuIcon which opens a Menu, showing an option to delete the item. The simplified code looks like this:

<List>
  <Menu
    open={Boolean(anchorEl)}
    anchorEl={anchorEl}
    ...>
      <MenuItem onClick={() => handleDelete(⚡collectionItem)}>Delete</MenuItem>
  </Menu>

  {myCollection.map((collectionItem) => (
    <ListItem secondaryAction={
      <IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
        <MoreVertIcon />
      </IconButton>
    }>
      {collectionItem.name}
    </ListItem>
  )}
</List>

My problem is that I need to know which item in myCollection was selected to pass it to the delete function. However, I don't have a reference to the current collectionItem in the myCollection array from the Menu. Moving the Menu into the map function makes no sense because multiple menus would be rendered. How can I solve this problem?


Solution

  • I solved it by giving the IconButtons custom HTML data attributes, e.g.

    <IconButton data-collection-id={collection.id} onClick={...}>
    ...
    </IconButton>
    

    Then, in the onClick function, we can retrieve it by using event.currentTarget.getAttribute("data-collection-id").