mui / material-ui

Material UI: Ready-to-use foundational React components, free forever. It includes Material UI, which implements Google's Material Design.
https://mui.com/material-ui/
MIT License
92.46k stars 31.85k forks source link

[Menu] Menu containing links #29371

Closed gat-cs closed 7 months ago

gat-cs commented 2 years ago

I am trying to use the Menu component to create a dropdown where some of the items are links (e.g. "My profile", "Log out", etc). The documentation (demo and api) does not mention this use case . I have so far found it impossible to achieve the following:

Current Behavior 😯

The obvious solution (<MenuItem component={Link}>) behaves as expected, but generates invalid html. Other solutions are broken in different ways.

Expected Behavior 🤔

Have a clear way to include links in a Menu, that behaves as expected with both keyboard and mouse, and generates valid html.

Steps to Reproduce 🕹

Steps:

  1. See code sandbox: https://codesandbox.io/s/basicmenu-material-demo-forked-6w0jp?file=/demo.js

Context 🔦

In the topbar, when the user clicks on their avatar, a menu should pop up containing some links (their profile, settings, logout) as well as buttons. The result should be valid html and behave as expected with both keyboard and mouse.

Your Environment 🌎

See code sandbox. Tested in Firefox.

siriwatknp commented 2 years ago

The obvious solution () behaves as expected, but generates invalid html.

What is the expected HTML structure that you are looking for? and please you provide the resource for that reference.

gat-cs commented 2 years ago

Hi,

I would like to be able to achieve what is described here: https://www.w3.org/TR/wai-aria-practices/examples/menu-button/menu-button-links.html.

<ul id="menu2"
      role="menu"
      aria-labelledby="menubutton">
    <li role="none">
      <a role="menuitem" href="https://www.w3.org/">
        W3C Home Page
      </a>
    </li>
    <li role="none">
      <a role="menuitem" href="https://www.w3.org/standards/webdesign/accessibility">
        W3C Web Accessibility Initiative
      </a>
    </li>
</ul>

The last example in the codesandbox shows that this HTML structure can be achieved, however the keyboard behavior is broken:

Additionally, I would expect to be able to mix links and button in the same menu (for example, some menu items navigate somewhere, others trigger a dialog).

hata6502 commented 2 years ago

(For Material-UI v4)

To make keyboard focus with the valid HTML structure, I programmed as below:

<Menu
  MenuListProps={{
    // @ts-expect-error https://github.com/mui-org/material-ui/issues/17579
    component: "nav"
  }}
>
  <MenuItem component="div">
    Plain text
  </MenuItem>

  <MenuItem component={Link}>
    Link
  </MenuItem>
</Menu>

This example code is based on https://v4.mui.com/components/lists/#simple-list