From e2c6cd83c9ca770bbd1b16029987d97f88facf14 Mon Sep 17 00:00:00 2001
From: crupest <crupest@outlook.com>
Date: Mon, 5 Jul 2021 22:27:30 +0800
Subject: refactor: Extract out useClickOutside.

---
 FrontEnd/src/views/common/menu/PopupMenu.tsx | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

(limited to 'FrontEnd/src/views/common/menu/PopupMenu.tsx')

diff --git a/FrontEnd/src/views/common/menu/PopupMenu.tsx b/FrontEnd/src/views/common/menu/PopupMenu.tsx
index d7b81f49..fce97fcd 100644
--- a/FrontEnd/src/views/common/menu/PopupMenu.tsx
+++ b/FrontEnd/src/views/common/menu/PopupMenu.tsx
@@ -3,6 +3,8 @@ import React from "react";
 import { createPortal } from "react-dom";
 import { usePopper } from "react-popper";
 
+import useClickOutside from "@/utilities/useClickOutside";
+
 import Menu, { MenuItems } from "./Menu";
 
 import "./PopupMenu.css";
@@ -28,22 +30,7 @@ const PopupMenu: React.FC<PopupMenuProps> = ({
     React.useState<HTMLDivElement | null>(null);
   const { styles, attributes } = usePopper(referenceElement, popperElement);
 
-  React.useEffect(() => {
-    const handler = (event: MouseEvent): void => {
-      let element: HTMLElement | null = event.target as HTMLElement;
-      while (element) {
-        if (element == referenceElement || element == popperElement) {
-          return;
-        }
-        element = element.parentElement;
-      }
-      setShow(false);
-    };
-    document.addEventListener("click", handler);
-    return () => {
-      document.removeEventListener("click", handler);
-    };
-  }, [referenceElement, popperElement]);
+  useClickOutside(popperElement, () => setShow(false));
 
   return (
     <>
-- 
cgit v1.2.3

