From 253db8304a2237831ff73e1e39c17d9f228470e5 Mon Sep 17 00:00:00 2001 From: Trevor Buckner Date: Mon, 16 May 2022 23:07:38 -0400 Subject: [PATCH] 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. --- shared/naturalcrit/nav/nav.jsx | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/shared/naturalcrit/nav/nav.jsx b/shared/naturalcrit/nav/nav.jsx index 46ea5f27c..ef7d387e9 100644 --- a/shared/naturalcrit/nav/nav.jsx +++ b/shared/naturalcrit/nav/nav.jsx @@ -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 (
{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)}