Material-ui: open menu by event hover

Caio Batista picture Caio Batista · Dec 15, 2017 · Viewed 21.3k times · Source

Currently the menuItem only opens your children after a click. Is there an attribute that I agree to open via Hover?

<MenuItem key={index}
  menuItems={menuitems}
  **onHover={true}**
>
 menuItem
</MenuItem>

Answer

Jules Dupont picture Jules Dupont · Dec 16, 2017

There is not specific attribute available through the material-ui library. However, you could create this yourself pretty easily using the onMouseOver event.

I've adapted the Simple Menu example from the material-ui site to show you how this can be done:

import React from 'react';
import Button from 'material-ui/Button';
import Menu, { MenuItem } from 'material-ui/Menu';

class SimpleMenu extends React.Component {
  state = {
    anchorEl: null,
    open: false,
  };

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

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

  render() {
    return (
      <div>
        <Button
          aria-owns={this.state.open ? 'simple-menu' : null}
          aria-haspopup="true"
          onClick={this.handleClick}

          { // The following line makes the menu open whenever the mouse passes over the menu }
          onMouseOver={this.handleClick}
        >
          Open Menu
        </Button>
        <Menu
          id="simple-menu"
          anchorEl={this.state.anchorEl}
          open={this.state.open}
          onRequestClose={this.handleRequestClose}
        >
          <MenuItem onClick={this.handleRequestClose}>Profile</MenuItem>
          <MenuItem onClick={this.handleRequestClose}>My account</MenuItem>
          <MenuItem onClick={this.handleRequestClose}>Logout</MenuItem>
        </Menu>
      </div>
    );
  }
}

export default SimpleMenu;