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:
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!
JavaScript
x
18
18
1
<Menu
2
id="order-menu"
3
anchorEl={anchorEl}
4
keepMounted
5
open={Boolean(anchorEl)}
6
onClose={() => setAnchorEl(null)}
7
>
8
{options.map((option, index) => (
9
<MenuItem
10
key={option}
11
selected={index === selectedIndex}
12
onClick={(event) => handleMenuItemClick(event, index)}
13
>
14
{option}
15
</MenuItem>
16
))}
17
</Menu>
18
Advertisement
Answer
The default styles controlling this are in ListItem
where it specifies justifyContent: ‘flex-start’.
You can change this to be right aligned with:
JavaScript
1
6
1
const MenuItem = withStyles({
2
root: {
3
justifyContent: "flex-end"
4
}
5
})(MuiMenuItem);
6
Here’s a full working example:
JavaScript
1
50
50
1
import React from "react";
2
import Button from "@material-ui/core/Button";
3
import Menu from "@material-ui/core/Menu";
4
import MuiMenuItem from "@material-ui/core/MenuItem";
5
import { withStyles } from "@material-ui/core/styles";
6
7
const MenuItem = withStyles({
8
root: {
9
justifyContent: "flex-end"
10
}
11
})(MuiMenuItem);
12
13
export default function SimpleMenu() {
14
const [anchorEl, setAnchorEl] = React.useState(null);
15
16
const handleClick = event => {
17
setAnchorEl(event.currentTarget);
18
};
19
20
const handleClose = () => {
21
setAnchorEl(null);
22
};
23
24
return (
25
<div>
26
<Button
27
aria-controls="simple-menu"
28
aria-haspopup="true"
29
onClick={handleClick}
30
>
31
Open Menu
32
</Button>
33
<Menu
34
id="simple-menu"
35
anchorEl={anchorEl}
36
keepMounted
37
open={Boolean(anchorEl)}
38
onClose={handleClose}
39
>
40
<MenuItem onClick={handleClose}>1</MenuItem>
41
<MenuItem onClick={handleClose}>2</MenuItem>
42
<MenuItem onClick={handleClose}>3</MenuItem>
43
<MenuItem onClick={handleClose}>10</MenuItem>
44
<MenuItem onClick={handleClose}>20</MenuItem>
45
<MenuItem onClick={handleClose}>300</MenuItem>
46
</Menu>
47
</div>
48
);
49
}
50
Related documentation: