Skip to content

How to align Material-UI Menu items?

I use the menu and menu item of material-ui to build a select dropdown menu, but I found one thing strange: the dropdown menu always expand to the left side of the box, as the image shown below: enter image description here

I’ve tried to use the alignItems property inside my <MenuItem> but it didn’t work.

My code is shown below. Can anybody help me to fix this problem? I really appreciate your help!

          <Menu
            id="order-menu"
            anchorEl={anchorEl}
            keepMounted
            open={Boolean(anchorEl)}
            onClose={() => setAnchorEl(null)}
          >
            {options.map((option, index) => (
              <MenuItem
                key={option}
                selected={index === selectedIndex}
                onClick={(event) => handleMenuItemClick(event, index)}
              >
                {option}
              </MenuItem>
            ))}
          </Menu>

Answer

The default styles controlling this are in ListItem where it specifies justifyContent: ‘flex-start’.

You can change this to be right aligned with:

const MenuItem = withStyles({
  root: {
    justifyContent: "flex-end"
  }
})(MuiMenuItem);

Here’s a full working example:

import React from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MuiMenuItem from "@material-ui/core/MenuItem";
import { withStyles } from "@material-ui/core/styles";

const MenuItem = withStyles({
  root: {
    justifyContent: "flex-end"
  }
})(MuiMenuItem);

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}>1</MenuItem>
        <MenuItem onClick={handleClose}>2</MenuItem>
        <MenuItem onClick={handleClose}>3</MenuItem>
        <MenuItem onClick={handleClose}>10</MenuItem>
        <MenuItem onClick={handleClose}>20</MenuItem>
        <MenuItem onClick={handleClose}>300</MenuItem>
      </Menu>
    </div>
  );
}

Edit MenuItem align right

Related documentation: