Reputation: 23
I am using Menu and Menu Item from MaterialUI in React. I want to print the name of the menu item when I click on it.
In the console.log event.currentTarget returns the entire list item: ListItem Image attached
In the console.log event.currentTarget.dataset returns the DOMSTringMap. WRT a similar question I found: Get value of MenuItem material ui But the output of DOMStringMap seems unusable.
Check the addMap function: I want to console.log the name of the menu item which is "ONE".
import React from 'react';
import { useState } from 'react';
import {IconButton, Menu, MenuItem } from '@material-ui/core';
const options = [
'ONE',
'TWO',
'THREE',
];
const ITEM_HEIGHT = 48;
export default function AdvanceOptionsMenu() {
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);
const [mapList, setMapList] = useState([]);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const addMap = (event) => {
**console.log(event.currentTarget)**
handleClose();
};
return (
<>
<div className="advance-menu">
<IconButton
aria-label="more"
aria-controls="long-menu"
aria-haspopup="true"
onClick={handleClick}
>
<MoreVert />
</IconButton>
<Menu
id="long-menu"
anchorEl={anchorEl}
keepMounted
open={open}
onClose={handleClose}
PaperProps={{
style: {
maxHeight: ITEM_HEIGHT * 4.5,
width: '20ch',
},
}}
>
{options.map((option) => (
<MenuItem key={option} selected={option==="ONE"} onClick={addMap}>
{option}
</MenuItem>
))}
</Menu>
</div>
{mapList}
</>
);
}
Upvotes: 2
Views: 5236
Reputation: 1707
The question link you shared, one of the answers suggested using the event.target.innerText
to get the value. Another approach could be, you can pass a value to the onClick
in the MenuItem
. I've created a demo for both options. Please review.
Upvotes: 2