Search code examples
reactjsmaterial-uiz-index

How can I close a modal and its dropdow in one click MUI


I want to know if it's possible to close both a modal that I open after click and its dropdown menu in one click.

I have the screenshot below and the link to a sandbox here : https://codesandbox.io/s/eloquent-murdock-nwewl4?file=/src/App.tsx

Screenshot

I can open the pop up by clicking on the hand icon. Then I can open the dropdown menu by clicking on the Theme input.

I have attached a backdrop that opens the first pop up that can be clicked to close the same pop up. Right now there is a backdrop for both the pop up and the select dropdown. So I can only close the select dropdown first then the pop up.

I am using the MUI library so that's why I found myself stuck in doing that. I believe it is a matter of z-index. I have read the MUI documentation, and I saw that a MUI modal's z-index is 1300.

I want to know if it's possible to close both the pop up and the select dropdown menu at the same time if I click on the backdrop for a better UX.

I have tried different ways

  1. I have added the MenuProps and PaperProps ( with and without the !important keyword ) to try and reduce the z-index of the dropdown. Only the background changed to red. I didn't see any other changes.

`

<Select labelId="theme-label" id="theme-checkbox" value={age} label="Age" onChange={handleChange} MenuProps={{ sx:{ zIndex: '1 !important',}, PaperProps: {  sx: {  zIndex: '1 !important', background: 'red', '& .MuiMenuItem-root': {  zIndex: '1 !important', }, }, }, }} >
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>

`

  1. I have also tried playing with the classes from the library to try and remove the dropdown select's backdrop which I believe is a bad practice, and I could not interact with the Theme input anymore when I added the piece of code.

`

.css-10nakn3-MuiModal-root-MuiPopover-root-MuiMenu-root{
    position: static !important;

}

`

  1. I have tried different methods using the !important keyword, but I didn't see any results.

I have been on SO for a while but barely posted. I am trying to learn react right now and would appreciate if someone can help me. Thanks in advance!

Edit: changed screenshot description


Solution

  • You can use onClose of MUI Select

    Here is the code

    <Select
      labelId="theme-label"
      id="theme-checkbox"
      value={age}
      label="Age"
      onChange={handleChange}
      onClose={()=>setToggleMenu(false)}
        >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
     </Select>