How to Detect a Click Outside a React Component?

best way to use React hooks

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.

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.


import React, { useRef, useEffect } from "react";

import PropTypes from "prop-types";

function outSide(open) {

useEffect(() => {

function handleClickOutside(event) {

if (open.current && !open.current.contains( {

alert("Show alert Box!");



document.addEventListener("mousedown", handleClickOutside);

return () => {

document.removeEventListener("mousedown", handleClickOutside);


}, [open]);


function outSideClick(props) {

const wrapperRef = useRef(null);




; } outSideClick.propTypes = { children: PropTypes.element.isRequired }; export default outSideClick;


<button>Click Outside</button>

Click outside:





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.


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.





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 by user.

Bosc Tech Labs


John Elger is a senior manager at Bosc Tech Labs, which is preffered Flutter development company in USA.
4.7 Star App Store Review!***uke
The Communities are great you rarely see anyone get in to an argument :)
Love Love LOVE

Select Collections