I want to close a dropdown menu when a click occurs outside of the dropdown component.
How do I do that?
We need to detect a click outside a React component to implement a solution for this scenario. First, we'll create a new React app to get started. You can alternatively add the following outside click detection code to your existing React app. Enter the following command and create a new app.
To detect click outside element with JavaScript, we can use the element's contains method. const specifiedElement = document. getElementById("a"); document. addEventListener("click", (event) => { const isClickInside = specifiedElement.
To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs. Approach: Here the approach is to use @HostListener decorator.
jQuery closest() is used to see if the target from a click event has the dom element as one of its parents.
Using the life-cycle methods add and remove event listeners to the document.
React.createClass({ handleClick: function (e) { if (this.getDOMNode().contains(e.target)) { return; } }, componentWillMount: function () { document.addEventListener('click', this.handleClick, false); }, componentWillUnmount: function () { document.removeEventListener('click', this.handleClick, false); } });
Check out lines 48-54 of this component: https://github.com/i-like-robots/react-tube-tracker/blob/91dc0129a1f6077bef57ea4ad9a860be0c600e9d/app/component/tube-tracker.jsx#L48-54
In the element I have added mousedown
and mouseup
like this:
onMouseDown={this.props.onMouseDown} onMouseUp={this.props.onMouseUp}
Then in the parent I do this:
componentDidMount: function () { window.addEventListener('mousedown', this.pageClick, false); }, pageClick: function (e) { if (this.mouseIsDownOnCalendar) { return; } this.setState({ showCal: false }); }, mouseDownHandler: function () { this.mouseIsDownOnCalendar = true; }, mouseUpHandler: function () { this.mouseIsDownOnCalendar = false; }
The showCal
is a boolean that when true
shows in my case a calendar and false
hides it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With