I am trying to use MUI to create a MenuItem
+ Link
with a nested Typography
component that will navigate to the link on click.
Currently I am using the Responsive App Bar here as a template.
Here is the code I currently have for the open/close menu + states, as well as the component I've defined for making links in the hamburger menu.
const [anchorElNav, setAnchorElNav] = React.useState(null);
const [anchorElUser, setAnchorElUser] = React.useState(null);
const handleOpenNavMenu = (event) => {
setAnchorElNav(event.currentTarget);
};
const handleOpenUserMenu = (event) => {
setAnchorElUser(event.currentTarget);
};
const handleCloseNavMenu = () => {
setAnchorElNav(null);
};
const handleCloseUserMenu = () => {
setAnchorElUser(null);
};
const HamburgerMenuLink = ({ text, href }) => {
return (
<MenuItem component={Link} to={href} onClick={handleCloseNavMenu}>
<Typography textAlign="center">{text}</Typography>
</MenuItem>
);
};
Here is where the Menu
+ HamburgerMenuLink
is implemented:
<Menu
id="menu-appbar"
anchorEl={anchorElNav}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
open={Boolean(anchorElNav)}
onClose={handleCloseNavMenu}
sx={{
display: { xs: "block", md: "none" },
}}
>
<HamburgerMenuLink text="Beers" href="/beer" />
<HamburgerMenuLink text="My Beers" href="/beer/me" />
<HamburgerMenuLink text="New Beer" href="/beer/new" />
</Menu>
I have tried the following:
HamburgerMenuLink
in a Link
componentcomponent={Link}
prop to the nested Typography
instead of MenuItem
Neither of these resulted in navigating to the route in the to
prop
The component
prop does not expect a actual Component, it expects a elementType. See the MenuItem props.
So what you can do is pass a "a"
to the component
prop and simply use the href
as you would on a a
tag.
const HamburgerMenuLink = ({ text, href }) => {
return (
<MenuItem component={"a"} href={href} onClick={handleCloseNavMenu}>
<Typography textAlign="center">{text}</Typography>
</MenuItem>
);
};