Hamza Bouallegue
Hamza Bouallegue

Reputation: 121

how to close a popupState menu and call a function on same onClick

I m using react mterial-ui when i call a function onClick on menu item the menu still open

      myFn(){
        // some code here 
        }
        render(){  
        return (
            <PopupState variant="popover" popupId="demo-popup-menu">
              {(popupState) => (
                <React.Fragment>
                  <Button variant="contained" color="primary" {...bindTrigger(popupState)}>
                    Open Menu
                  </Button>
                  <Menu {...bindMenu(popupState)}>
            {/*The menu must be closed when myFn is called */}
                    <MenuItem onClick={()=>myFn()}>Cake</MenuItem>
                    <MenuItem onClick={popupState.close}>Death</MenuItem>
                  </Menu>
                </React.Fragment>
              )}
            </PopupState>
          );
        }

I followed this example https://material-ui.com/components/menus/#popupstate-helper

Upvotes: 1

Views: 1930

Answers (3)

Sarun UK
Sarun UK

Reputation: 6746

Try below approach,

class MenuPopupState extends Component {
    handleClick = (popupState) => {
      // Your logic here
      popupState.close();
   };

  render() {
    return (
      <PopupState variant="popover" popupId="demo-popup-menu">
        {(popupState) => (
          <React.Fragment>
            <Button
              variant="contained"
              color="primary"
              {...bindTrigger(popupState)}
            >
              Open Menu
            </Button>
            <Menu {...bindMenu(popupState)}>
              <MenuItem
                onClick={() => {
                  this.handleClick(popupState);
                }}
              >
                Cake
              </MenuItem>
              <MenuItem onClick={popupState.close}>Death</MenuItem>
            </Menu>
          </React.Fragment>
        )}
      </PopupState>
    );
  }
}

export default MenuPopupState;

Sample Code - https://codesandbox.io/s/material-demo-forked-qguj6?file=/demo.js

Upvotes: 1

Jose E. Saura
Jose E. Saura

Reputation: 1

try to do an arrow on the onclick.

 <MenuItem onClick={() => popupState.close}>Death</MenuItem>

You should always do onClick like this.

Also, if you want to close it from your function myFunc() you should call the popupState.close from inside.

try it and tell us :-)

Upvotes: 0

helrabelo
helrabelo

Reputation: 551

If "popupState" is, in fact, a state.

Your onClick function should be setting that state to "false"

Can you provide more code? We don't have much information based on what you posted.

Upvotes: 0

Related Questions