How to Detect a Click Outside a React Component?
Tags: react, programming, beginners, tutorial
Published: 2022-06-21 11:58:24

Today we are going to see how you can detect a click outside of a React component. We will understood this topic by creating a custom React hook for it. For example, Consider a case when you want custom React hook for dropdown or dialog components that need to close when user clicks outside of them. So, in this article we’ll figure out the way to find out this outside click.

We can use the contains API to see if a target node is contained within another node. That is, it will return true if the clicked component is within the component we are interested in and false otherwise.

A React component is a JSX-based UI building unit self-contained, reusable, and separated.

Web developers also use custom dropdowns to allow users to choose from a list of alternatives. As we have seen earlier the components like custom dropdown should be close while user clicks outside when it is open. To build an enterprise-level application or implement these solutions, you can easily consult or hire react developers from bosctechlabs.com.

##Detecting an outside click of a functional component

Let’s make an HTML tooltip by using the InfoBox React functional component.

When the user hits a button, the tooltip appears, and when the user clicks outside of the tooltip component, it disappears. We will try to detect click outside the React component for the solution of this question.

To get started, we’ll construct a new React app. You can also use the code below to detect outside clicks in your existing React app.

##Example:

```javascript
import React, { useRef, useEffect } from "react";
import PropTypes from "prop-types";
 
function outSide(open) {
  useEffect(() => {
 
    function handleClickOutside(event) {
      if (open.current && !open.current.contains(event.target)) {
        alert("Show alert Box!");
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [open]);
}
 
function outSideClick(props) {
  const wrapperRef = useRef(null);
  outSide(wrapperRef);
 
  return;
{props.children}
; } outSideClick.propTypes = { children: PropTypes.element.isRequired }; export default outSideClick;
```
##Output
<button>Click Outside</button>

**Click Outside:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxxtxsw53o4dy6hdslqs.png)


**UseRef:** The useRef hook allows the functional component to create a direct reference to the DOM element.

**Syntax:**

```javascript
const refContainer = useRef(initialValue);
```
**UseRef:** The useRef hook allows the functional component to create a direct reference to the DOM element.

**Syntax:**

```javascript
const refContainer = useRef(initialValue);
```
The useRef returns a mutable ref object. This object has a property called .current. The refContainer.current property keeps track of the value. The current property of the returned object is used to access these values.

**UseEffect:** React useEffect is a function that is executed for 3 different React component lifecycles which we will see below.

1. componentDidMount
2. componentDidUpdate
3. componentWillUnmount

**1. componentDidMount:**
We started fixing fetch calls before the class Component and even inside the render() method when we made made our first React component.

This had strange negative effects on the application, causing groan.

**2. componentDidUpdate:**
This React lifecycle is called immediately after a prop or state change has occurred.

It signifies we clicked inside our worried element if the element that triggered the mouse down event is either our concerned element or any element that is inside the concerned element.

**Example:**

```html
Index.html:
<!DOCTYPE html>
<html>
  <head>
    <title> </title>
  </head>
  <body>
      <section>
        <div id=’click-text’>
          Click Me and See Console
        </div>  </section>
  </body>
</html>
```
**DetectElement.js:**

```javascript
const DetectElement = document.querySelector(".click-text");
 
document.addEventListener("mousedown", (e) => {
  if (DetectElement.contains(e.target)) {
    console.log("click inside");
  } else {
    console.log("click outside");
  }
});
```
##Output

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xc2cu7zz5e7iigqy8yu9.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chhh7m6e0o2ggwpn0dz1.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cg3aq7eju342bed3nwuj.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vap9vwn4t3ee9fjfrxg9.png)

##Conclusion
So far, we have seen that how you can detect a click outside the the React components using the custom React hook. Also, we have learned to utilize UseEffet hook and UseRef hook while detecting the outside click bu user.

Thank you for reading the article. Hope you enjoyed the Reading.