I am trying to open and close my Material UI <Menu />
by using React's setState hook. I used this sandbox code as an example. My implementation doesn't seem to close the menu however.
Opening it works fine (using setAnchorEl(event.currentTarget)
), but closing it using setAnchorEl(null)
does not somehow. The function handleClose()
runs (the console.log()
prints fine), but the value of anchorEl
does not change. I checked this using the useEffect()
hook, which prints null on initialization, the <li>
element when opening and nothing when trying to close.
I already tried using let
instead of const
for the (set
)anchorEl
and isProfileMenuOpen
definition, but this doesn't work. I also checked out this post, but my <MenuAppBar />
component is not being unmounted as far as I can see (it's rendered at the root unconditionally).
I must be overlooking some detail. Can anybody spot it below?
const {useState, useEffect} = React;
const { ClickAwayListener, Menu, MenuItem, IconButton } = MaterialUI;
function MenuAppBar(props) {
const [anchorEl, setAnchorEl] = useState(null);
const isProfileMenuOpen = Boolean(anchorEl);
// For debugging purposes:
useEffect(() => {
console.log(anchorEl);
}, [anchorEl]);
const handleClose = () => {
console.log("Closing menu"); // This prints, so function runs
setAnchorEl(null); // This doesn't seem to set anchorEl to null
};
const handleProfileMenuOpen = (event) => {
setAnchorEl(event.currentTarget); // This does work
}
return (
<ClickAwayListener onClickAway={handleClose}>
<MenuItem onClick={handleProfileMenuOpen}>
<IconButton
style={{ backgroundColor: "#F5B089" }}
/>
<Menu
anchorEl={anchorEl}
keepMounted
open={isProfileMenuOpen}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem>Logout</MenuItem>
</Menu>
</MenuItem>
</ClickAwayListener>
);
}
ReactDOM.render(
<MenuAppBar />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<div id="react"></div>