Function useOutsideClick

  • Custom React hook that detects clicks outside a specified element.

    This hook listens for mousedown events on the document. If a click occurs outside of the referenced element, the provided callback function is executed. It is useful for implementing dropdowns, modals, or any UI element that requires detecting clicks outside to close or hide the element.

    Example

    const MyComponent = () => {
    const ref = useRef<HTMLDivElement>(null);

    const handleOutsideClick = (event: MouseEvent) => {
    console.log('Clicked outside:', event);
    };

    useOutsideClick(ref, handleOutsideClick);

    return <div ref={ref}>Click outside me!</div>;
    };

    Parameters

    • ref: THookEventElement<Element>

      A reference to the element to monitor for outside clicks.

    • callback: ((event) => void)

      The callback function to be called when an outside click is detected.

        • (event): void
        • Parameters

          • event: MouseEvent

          Returns void

    • Optional props: IUseOutsideClickProps

      Optional settings for managing the event listener behavior.

    Returns void