0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-28 00:32:42 +00:00

Make dropdown close on clickoutside, not mouseout

Accomplished by adding an onClick event listener to the whole document and then closing if the click was not inside the dropdown.
This commit is contained in:
Trevor Buckner
2022-05-16 23:07:38 -04:00
parent a17a9ac0a0
commit 253db8304a

View File

@@ -83,6 +83,20 @@ const Nav = {
showDropdown : false
};
},
componentDidMount : function() {
if(this.props.trigger == 'click')
document.addEventListener('click', this.handleClickOutside);
},
componentWillUnmount : function() {
if(this.props.trigger == 'click')
document.removeEventListener('click', this.handleClickOutside);
},
handleClickOutside : function(e){
// Close dropdown when clicked outside
if(this.refs.dropdown && !this.refs.dropdown.contains(e.target)) {
this.handleDropdown(false);
}
},
handleDropdown : function(show){
this.setState({
showDropdown : show
@@ -105,9 +119,10 @@ const Nav = {
});
return (
<div className={`navDropdownContainer ${this.props.className}`}
ref='dropdown'
onMouseEnter={this.props.trigger == 'hover' ? ()=>{this.handleDropdown(true);} : undefined}
onClick= {this.props.trigger == 'click' ? ()=>{this.handleDropdown(true);} : undefined}
onMouseLeave={()=>this.handleDropdown(false)}>
onMouseLeave={this.props.trigger == 'hover' ? ()=>{this.handleDropdown(false);} : undefined}>
{this.props.children[0] || this.props.children /*children is not an array when only one child*/}
{this.renderDropdown(dropdownChildren)}
</div>