CSS Position Material UI Menu item below its parent
I've got a Material UI dialog that contains nothing but some text and an Icon with a Menu options dropdown. The demo can be seen here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js
I'm trying to position the Menu
component so that it appears just below the Settings
component when it is clicked. I've specified a position: relative
on the parent element (i.e. the Settings
Icon) as well as a position: absolute
with top: -10px
to the child element (i.e the Menu
component), but that doesn't seem to work.
How can I set it up so that when the Settings icon is clicked, the Menu appears directly below the Settings, as well as when the window is resized so that the Menu follows?
EDIT:
In case there are any problems with opening the codesandbox, this is what I have.
App.js:
import "./styles.css";
import { useState } from "react";
import {
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
ListItemText,
Menu,
MenuItem
} from "@material-ui/core";
import Settings from "@material-ui/icons/Settings";
export default function App() {
const [openMenu, setOpenMenu] = useState(false);
return (
<div className="App">
<h1 className="blueFont">Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Dialog fullWidth maxWidth="sm" open={true} hideBackdrop={true}>
<DialogTitle style={{ height: "60px" }}>My title</DialogTitle>
<DialogContent>My Content</DialogContent>
<Divider style={{ width: "100%" }} />
<DialogActions>
<div className="settings">
<Settings onClick={() => setOpenMenu(!openMenu)} />
<div className="menu">
<Menu open={openMenu}>
<MenuItem>
<ListItemText>First option</ListItemText>
</MenuItem>
<MenuItem>
<ListItemText>Second option</ListItemText>
</MenuItem>
</Menu>
</div>
</div>
</DialogActions>
</Dialog>
</div>
);
}
styles.css
.App {
font-family: sans-serif;
text-align: center;
}
.blueFont {
color: blue;
}
.settings {
position: relative;
}
.menu {
position: absolute;
top: -10px;
}
Solution 1:
You can also refer documentation
https://mui.com/components/menus
I've also created a sandbox
https://codesandbox.io/s/elastic-hooks-0fi6z?file=/src/App.js
const [anchorEl, setAnchorEl] = useState(null);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const open = Boolean(anchorEl);
<DialogActions>
<div>
<Button id="basic-button" onClick={handleClick}>
Dashboard <Settings />
</Button>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
anchorOrigin={{
vertical: "top",
horizontal: "left"
}}
transformOrigin={{
vertical: "top",
horizontal: "left"
}}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
</DialogActions>