Open menu on mouseover and Close menu on mouseleave in react
The flickering is caused by the opening of the menu underneath your mouse. When the menu opens, the mouse is no longer over the button, so it prompts a mouseleave
event, closing the menu, so that your mouse is now above the button again, prompting a mouseenter
event, which opens the menu...and so on and so forth.
You can accomplish what you'd like with some additional logic to track where the mouse is, and a timeout to ensure that the user has time to transition the mouse between the button and the menu.
import React from 'react';
import Button from 'material-ui/Button';
import Menu, { MenuItem } from 'material-ui/Menu';
const timeoutLength = 300;
class SimpleMenu extends React.Component {
state = {
anchorEl: null,
// Keep track of whether the mouse is over the button or menu
mouseOverButton: false,
mouseOverMenu: false,
};
handleClick = event => {
this.setState({ open: true, anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ mouseOverButton: false, mouseOverMenu: false });
};
enterButton = () => {
this.setState({ mouseOverButton: true });
}
leaveButton = () => {
// Set a timeout so that the menu doesn't close before the user has time to
// move their mouse over it
setTimeout(() => {
this.setState({ mouseOverButton: false });
}, timeoutLength);
}
enterMenu = () => {
this.setState({ mouseOverMenu: true });
}
leaveMenu = () => {
setTimeout(() => {
this.setState({ mouseOverMenu: false });
}, timeoutLength);
}
render() {
// Calculate open state based on mouse location
const open = this.state.mouseOverButton || this.state.mouseOverMenu;
return (
<div>
<Button
aria-owns={this.state.open ? 'simple-menu' : null}
aria-haspopup="true"
onClick={this.handleClick}
onMouseEnter={this.enterButton}
onMouseLeave={this.leaveButton}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={this.state.anchorEl}
open={open}
onClose={this.handleClose}
MenuListProps={{
onMouseEnter: this.enterMenu,
onMouseLeave: this.leaveMenu,
}}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
}
export default SimpleMenu;
I used the MenuListProps
to set the mouseEnter
and mouseLeave
events directly on the MenuList
itself because the Menu
component includes a bunch of invisible (disply: none
) transition elements that have weird effects on mouse events. The MenuList
is the element that's actually displayed so it makes sense to set the mouse events directly on it.
You'll probably need to play around with the timeoutLength
and transitions to get everything looking smooth.