Open menu on mouseover and Close menu on mouseleave in react

abidishajia picture abidishajia · Dec 28, 2017 · Viewed 15.7k times · Source

I just started plating around with react. I am currently working on my navBar using material-ui and react. When I hover over the menu, the drop-down appears. But in order to close the drop-down, I have to click on the outside of the drop-down. I want to be able to close the dropdown when I hover out of the drop-down or move to the different menu option (in which case a different drop-down should appear). Something like this one: https://www.palantir.com/

I looked around but I didn't find the solution. This was the closest I got: Material-ui: open menu by event hover

I tried using the same technique and added this to my code but to no avail. Any suggestions? Thanks!

Edits: I recreated my problem here: https://react-xmaiyw.stackblitz.io The problem can be seen when clicked on 'Why us'.

 handleClick = (event) => {
 event.preventDefault();

   this.setState({
    open: true,
    anchorEl: event.currentTarget,
   });
 };

handleRequestClose = () => {
  this.setState({
   open: false,
  });
};

render() {
return (
  <FlatButton
  onClick={this.handleClick}
  onMouseOver={this.handleClick}
  onMouseLeave={this.handleRequestClose} //When I add this line of 
     //code, it keeps flickering very fast almost as if drop-down 
     //doesn't open
  label="Why Us?"
/>
)}

Answer

Jules Dupont picture Jules Dupont · Dec 31, 2017

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.