I have added a Material UI open menu feature in a React app. However when you click the menu item in the app bar and the dropdown appears, it doesn't appear directly below the menu item. Not sure what im missing, I have included a snippet of the code below. Thanks
class Tester extends Component {
constructor(props){
super(props)
this.state = {
placeholder: []
}
}
openMenu(){
this.setState({
...this.state,
toggle: !this.state.toggle
})
}
return (
<Link className={classes.tester} onClick={() =>
{this.openMenu(this.state.toggle)}}>
Tester
</Link>
<Menu
id="simple-menu"
open={this.state.toggle}
onClose={() => {this.openMenu()}}>
<MenuItem>Profile</MenuItem>
<MenuItem >My account</MenuItem>
<MenuItem >Logout</MenuItem>
</Menu>
)
The menu must have an anchor to be able to appear next to this anchor. The prop is called anchorEl
.
You can follow the example from Material-UI docs:
import React from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
export default function SimpleMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);