Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing tab key closes Material UI Dialog that is opened from a submenu

I need to create a menubar with a number of menus that have submenus. When I open a dialog from a top level menu item, everything works as desired/expected. BUT when I open a dialog from a submenu, pressing the tab key closes the dialog.

I've tried several different ways of implementing the nested menus and settled on the approach discussed here: https://github.com/mui-org/material-ui/issues/11723

I've created sample code to demonstrate the problem here: https://codesandbox.io/s/loving-heisenberg-rvwwb You'll see this is forked from the submenu example I found on GitHub. There were a few things I changed because I wasn't sure how to add the opening of a dialog from that example, so I'm not sure the way I did it is correct.

like image 740
sweetpea Avatar asked Jan 26 '23 06:01

sweetpea


1 Answers

The problem is that Tab is triggering close of the parent Menu which then causes the Dialog to be unmounted. You could use state to prevent the parent Menu from closing whenever the Dialog is open, but that leaves a different problem. Regardless of whether the parent Menu closes, when a Tab occurs it calls event.preventDefault() which then prevents the Tab from changing the focus location (the default browser behavior).

You can fix this by having the Dialog stop propagation of the Tab key event. This prevents Menu from receiving it, so Menu won't try to close itself and it won't call event.preventDefault(). I can't guarantee that this won't introduce some new issues, but this fixes the issue described.

const stopPropagationForTab = (event) => {
  if (event.key === "Tab") {
    event.stopPropagation();
  }
};

      <Dialog
        onKeyDown={stopPropagationForTab}

Edit Cascading Menus with Dialog

In my fork of your sandbox, I upgraded the Material-UI version from 1.2 to 4.0 just because I wanted to make sure the issues weren't related to aspects that have changed. This threw off some of the styling, but the main behavior being addressed seemed to work the same in both versions.


A different way to handle this problem would be to rework the code such that the Dialog is no longer a child of the Menu. Then clicking a menu item that opens a Dialog would set state at the top-level for closing all the menus and opening the Dialog. This would probably be a better way to handle this, but it is a bigger change to the code structure.

like image 158
Ryan Cogswell Avatar answered May 05 '23 09:05

Ryan Cogswell