How to detect clicks outside a React component using a custom hook

Most web applications react to click events in different ways, and detecting exactly where the click is is important for the UI to function properly.

Many user interfaces use event-based appearance elements such as button clicks. When working with such a component, you'll want a way to hide it, usually in response to a click outside of its boundary.

This type of pattern is especially useful with elements like modals or sliding menus.

Handling clicks outside an element

Suppose you have the following markup in your application and want to close the inner element when the outer element is clicked:

To handle clicks outside of an element, you need to attach an event listener to the outer element. Then when the click event occurs, access that event object and check its target property.

If the event target does not contain an inner element, it means the click event was not fired on the inner element. In this case, you should remove or hide the inner element from the DOM.

Here is a tutorial that explains in detail how to handle clicks outside of an element. To see how this works in a React app, you need to create a new React project using Vite.

You can create projects using other methods, or simply use an existing project.

Handling clicks outside of an element in a React app

At the base of the project, create a new file named Home.jsx and add the following code to create a div that will hide when you click on that section.

import { useEffect, useRef } from "react"; export const Home = () => { const outerRef = useRef(); useEffect(() => { const handleClickOutside = (e) => { if (outerRef.current && !outerRef.current.contains(e.target)) { // Hide the div or perform any desired action } }; document.addEventListener("click", handleClickOutside); return () => { document.removeEventListener("click", handleClickOutside); }; }, []); return ( ); };

This code uses the useRef hook to create an object named outerRef. It then references this object via the div element's ref attribute.

You can use the useEffect hook to add event listeners on the page. The listener here calls the handleClickOutside function when the user fires the click event listener. The useEffect hook also returns a cleanup function, which removes the event listener when the Home component disconnects. This ensures no memory leaks.

The handleClickOutside function checks if the event target is a div element. The ref object provides information about the element it references in an object named current. You can test it to see if the div element has triggered a listener by confirming that it doesn't contain event.target . If true, you can hide this div tag.

Create custom hooks to handle clicks outside of an element

A custom hook will allow you to reuse this functionality in multiple components without having to redefine the functionality each time.

This hook will accept 2 arguments, the callback function and the ref object .

In this hook, the callback function is the function that is called when you click in the space outside the target element. The ref object references the external component.

To create this hook, add a new file named useClickOutside to the project and add the following code:

import { useEffect } from "react"; export const useOutsideClick = (callback, ref) => { const handleClickOutside = (event) => { if (ref.current && !ref.current.contains(event.target)) { callback(); } }; useEffect(() => { document.addEventListener("click", handleClickOutside); return () => { document.removeEventListener("click", handleClickOutside); }; }); };

The above hook works the same way as the previous code example - detected an external click in the Home component. What's different here is that it's reusable.

To use it, import it into the Home component, and switch to the callback function and the ref object.

const hideDiv = () => { console.log("Hidden div"); }; useOutsideClick(closeModal, outerRef);

This method abstracts the click detection logic outside of a component and makes your code more readable.

Above is how to detect click outside a React component . Hope the article is useful to you.

3.5 ★ | 2 Vote