user1735921 user1735921 - 5 months ago 36
React JSX Question

React NavDropdown hides on click of any MenuItem

Hello I am using react bootstrap, NavDropdown.
I have a Navbar in my application, and I want to put NavDropdown in Navbar but the default behaviour of NavDropdown hides the dropdown on click anywhere.

Solutions I have Used:

evt.preventDefault();
evt.stopPropagation();


None of above is working for me.

My Code:

class CustomNavDropdown extends React.Component {

constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
handleClick(evt) {
evt.preventDefault();
evt.stopPropagation();
}
render() {
return (
<NavDropdown title={"Dropdown"}>
<MenuItem divider />
<MenuItem onClick={this.handleClick}>an item</MenuItem>
</NavDropdown>
);
}
}


So basically my problem is that my NavDropdown hides if I click anywhere, I want it to hide only when I click on the
<ul>
tag, not the
<li>
tag or anywhere else in the application.

Answer Source

I solved as follows:

class CustomNavDropdown extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {menuIsOpened: false}
    this.handleToggle = this.handleToggle.bind(this);
  }
  handleToggle(toggle) {
    //you code here, change state of menuIsOpened if you want to open or close
  }
  render() {
    return (
      <NavDropdown title={"Dropdown"} open={this.state.menuIsOpened} onToggle={this.handleToggle}>
        <MenuItem divider />
        <MenuItem onClick={this.handleClick}>an item</MenuItem>
      </NavDropdown>
    );
  }
}

I put up event onToggle which is supported by NavDropdown and then we can handle the event in handleToggle and do whatever with it where toggle is boolean.