How to prevent material ui menu item from closing on click

Viewed 20

I have a menu with a single menu item, that menu items is a text field with a button. The purpose is to enter some data, hit the button to save data, and close the menu by hitting close or the original button again. How can I prevent the MenuItem from closing the menu on click? And as well how can I add the functionality to close the MenuItem to a button. Thank you!!

function AppWindow() {




  const [settingsState, setSettingsState] = useState(false);

  const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);

  const handleClick = (event) => {

    setAnchorEl(event.currentTarget);
    event.currentTarget.stopPropagation();
    
    if(settingsState === true){
      console.log('true to false');
      setSettingsState(false);
    }

    else if(settingsState === false){
      console.log('false to true');
      setSettingsState(true);
    }
  };

  const handleClose = () => {
    setAnchorEl(null);
  };





return (
    <Box className="App">

      <Box className='AppContainer'>
      
          <Paper className='Application' elevation={24} sx={{backgroundColor: '#023453'}}>
              <Box sx={{margin: '1%'}}>
                  <Grid container>
                      <Grid item xs={11} sx={{color: '#d4e1ed'}}>
                          Name
                      </Grid>

                      <Grid item xs={1}>
                          <SettingsIcon onClick={handleClick}></SettingsIcon>
                              <Menu
                                id="basic-menu"
                                anchorEl={anchorEl}
                                open={open}
                                onClose={handleClose}
                                getContentAnchorEl={null}
                                anchorOrigin={{vertical: 'bottom', horizontal: ''}}
                                transformOrigin={{vertical: 'top', horizontal: 'right'}}
                                sx={{marginTop: '0.5%'}}

                              >
                                <MenuItem onClick={handleClose} sx={{}}><Settings /></MenuItem>
                          </Menu>
                      </Grid>
                  </Grid>

enter image description here

1 Answers

In order to do so, omit this line:

const open = Boolean(anchorEl);

Instead use another state to control the menu

Related