PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

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

 November 07, 2022     material-ui, menu, reactjs, typescript     No comments   

Issue

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").



Answered By - Tim Wagner
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing