'Close dropdown when clicking outside using javascript/reactjs
I've created a drop down menu and open the menu when the user clicks on the menu icon. I have done this using react states. How can i close the dropdown menu when user clicks outside the menu element?
Dropdown menu
class DropDown extends Component {
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
this.state = {
openmenu:false
}
};
myFunction(e) {
e.stopPropagation();
this.setState({
openmenu: !this.state.openmenu
})
}
render() {
return (
<div className="dropdown small_font" id="myDropdown" onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp}>
{/*<img src={settings} onClick={this.myFunction} className="user_settings_icon"></img>*/}
<i className="fa fa-cog user_settings_icon" style={{marginTop: '6px'}} onClick={this.myFunction}
aria-hidden="true"></i>
{this.state.openmenu?
<div className="dropdown-content" id="myDropdown2">
{/*<div id="myDropdown" className={this.props.actionDropDownCSS}>*/}
<a className="dropdown_item"><i className="fa fa-trash-o margin_right10px" aria-hidden="true"></i>Delete</a>
<a className="dropdown_item"><i className="fa fa-flag-o margin_right10px" aria-hidden="true"></i>Report</a>
<a className="dropdown_item"><i className="fa fa-minus-square-o margin_right10px" aria-hidden="true"></i>Unfriend</a>
<a className="dropdown_item"><i className="fa fa-sign-out margin_right10px" aria-hidden="true"></i>Leave group</a>
</div>:null
}
</div>
);
}
}
Solution 1:[1]
You can add an onBlur() event on the icon and write a function to close the menu
Something like this would work
this.closeMenu(){
this.setState({
openmenu: false
})
}
<i onBlur={this.closeMenu} />
Solution 2:[2]
To achive this easily, you can use libraries like react-bootstrap, antd etc.
import React from "react";
import { DropdownButton, Dropdown } from "react-bootstrap";
const CustomDropdown = () => (
<DropdownButton id="dropdown-basic-button" title="Dropdown button">
<Dropdown.Item href="#/action-1">Action</Dropdown.Item>
<Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
<Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
</DropdownButton>
);
export default CustomDropdown;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gokul |
| Solution 2 | Isuru Chandrasiri |
