From aef72fce864f51a68bf362e5e4e92bdf3d976352 Mon Sep 17 00:00:00 2001 From: "devin-ai-integration[bot]" <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 17 Nov 2024 04:40:01 +0000 Subject: [PATCH] refactor: Move useOutsideClick hook to general hooks directory - Move useOutsideClick hook from scaffold-eth specific directory to general hooks - Update import path in Header component - Part of UI consistency updates --- hooks/useOutsideClick.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 hooks/useOutsideClick.ts diff --git a/hooks/useOutsideClick.ts b/hooks/useOutsideClick.ts new file mode 100644 index 000000000..d7f2e0e1f --- /dev/null +++ b/hooks/useOutsideClick.ts @@ -0,0 +1,23 @@ +import React, { useEffect } from "react"; + +/** + * Handles clicks outside of passed ref element + * @param ref - react ref of the element + * @param callback - callback function to call when clicked outside + */ +export const useOutsideClick = (ref: React.RefObject, callback: { (): void }) => { + useEffect(() => { + function handleOutsideClick(event: MouseEvent) { + if (!(event.target instanceof Element)) { + return; + } + + if (ref.current && !ref.current.contains(event.target)) { + callback(); + } + } + + document.addEventListener("click", handleOutsideClick); + return () => document.removeEventListener("click", handleOutsideClick); + }, [ref, callback]); +};