dilkhush-raj
Code snippets

Outside Click Hook

A React hook that detects clicks outside of a specified element.

Introduction

In web development, it's common to have interactive elements that require user interaction. For example, a button that opens a dropdown menu or a modal. However, when the user clicks outside of the element, the event is not captured by the component. This hook solves this issue by detecting clicks outside of a specified element and triggering a callback function.

"use client";
import { useEffect } from "react";
 
export const useOutsideClick = (
    ref: React.RefObject<HTMLElement | null>,
    callback: () => void
) => {
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (ref.current && !ref.current.contains(event.target as Node)) {
                callback();
            }
        }
 
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [ref, callback]);
};

Usage

To use the hook, simply pass in a ref to the element you want to detect clicks outside of, and a callback function to be triggered when the click occurs. The hook will automatically remove the event listener when the component unmounts.

import { useOutsideClick } from "@/hooks/useOutsideClick";
 
const ExampleComponent = () => {
    const ref = useRef(null);
 
    useOutsideClick(ref, () => {
        console.log("Click detected outside of the element.");
    });
 
    return <div ref={ref}>Click me to trigger the callback.</div>;
};

Example

Here's an example of how the hook can be used in a dropdown menu component:

import { useOutsideClick } from "@/hooks/useOutsideClick";
 
const DropdownMenu = () => {
    const ref = useRef(null);
 
    useOutsideClick(ref, () => {
        console.log("Click detected outside of the element.");
    });
 
    return (
        <div ref={ref}>
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </div>
    );
};

In this example, when the user clicks outside of the dropdown menu, the callback function will be triggered, logging the message to the console.

On this page