Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for click events that are outside of a component

Tags:

reactjs

I want to close a dropdown menu when a click occurs outside of the dropdown component.

How do I do that?

like image 326
Allan Hortle Avatar asked May 23 '14 05:05

Allan Hortle


People also ask

How do you listen for click events that are outside of a component React?

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.

How do you listen to a click outside of an element?

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.

How do I detect a click outside an element angular?

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.

Which component can detect click as event?

jQuery closest() is used to see if the target from a click event has the dom element as one of its parents.


2 Answers

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

like image 111
i_like_robots Avatar answered Sep 21 '22 22:09

i_like_robots


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.

like image 28
Robbert van Elk Avatar answered Sep 20 '22 22:09

Robbert van Elk