Close popover by click event / Material UI

Viewed 14835

I'm using popover for my React Application. It works fine but I want to add a functionality of closing a popover by clicking one of menu items inside.

I can close a popover by clicking outside of a popover. Is it possible to close a popover by clicking one of menu items in a popover?

Current view

enter image description here

Code

class Home extends React.Component{

constructor(props){
    super(props);
    this.state = {
        open: false
    }
}

 handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();

this.setState({
  open: true,
  anchorEl: event.currentTarget,
 });
};

handleRequestClose = () => {
this.setState({
  open: false,
});
};

render(){
return(
<div>
<div id="PaymentPanel">
<div className="PaymentTitle">Spent Last 14 Days<button className="PaymentToggle" onClick={this.handleTouchTap}>▼</button></div>

  <Popover
      open={this.state.open}
      anchorEl={this.state.anchorEl}
      anchorOrigin={{horizontal: 'left', vertical: 'top'}}
      targetOrigin={{horizontal: 'right', vertical: 'top'}}
      onRequestClose={this.handleRequestClose}
    >
    <Menu>
       <p className="menuItem" onClick={this.clickHandle}>{!this.state.priceBar? "Spent Last 14 Days" : "Spent Last 14 Days"}</p>
       <p className="menuItem"  onClick={this.clickHandle}>{this.state.priceBar? "Spent Last 30 Days" : "Spent Last 30 Days"}</p>
    </Menu>
   </Popover>
   </div>
   </div>
    )
    }
   }
1 Answers

Call handleRequestClose method from clickHandle. I modified your code, look at working example here - https://jsfiddle.net/gjxyc315/

clickHandle = () => {
    this.handleRequestClose();
};
...

<p className="menuItem" onClick={this.clickHandle}>...</p>

You also can apply handleRequestClose method directly to onClick prop of menu-item tag. You will get the same result.

<p className="menuItem" onClick={this.handleRequestClose}>...</p>
Related