BOSC
How to detect a click outside a React component

How to Detect a Click Outside a React Component?

Today we are going to see how you can detect a click outside of a React component. We will understand this topic by creating a custom React hook for it. For example, consider a case where you want a custom React hook for dropdown or dialog components that need to close when the user clicks outside of them. So, in this article, we’ll figure out the way to find out this outside click. Checkout the best way to use React hooks that would be helpful to meet the quality.

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:

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

Click outside:

 

Outside Click Output
Outside Click Output

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

Syntax:

const refContainer = useRef(initialValue);

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

Syntax:

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:

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:

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

 

Detect Click Output
Detect Click Output

 

Click Button show console
Click Button show console

 

Click Button Outside Show Console
Click Button Outside Show Console

 

Final Console Output
Final Console Output

 

Conclusion

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

Thank you for reading the article. Hope you enjoyed the Reading. Keep visiting Bosc Tech Labs for more insightful content.