From 583e2eb8afe096aa2b3a0e8ed58a45743926b380 Mon Sep 17 00:00:00 2001 From: "Navy.gif" Date: Thu, 24 Nov 2022 00:00:50 +0200 Subject: [PATCH] close element if clicked outside --- src/components/UserControls.js | 43 ++++++++++++++++++++++++---------- src/util/ClickDetector.js | 35 +++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 13 deletions(-) create mode 100644 src/util/ClickDetector.js diff --git a/src/components/UserControls.js b/src/components/UserControls.js index 9c4f9eb..67a9903 100644 --- a/src/components/UserControls.js +++ b/src/components/UserControls.js @@ -1,24 +1,41 @@ -import React from "react"; +import React, { useRef } from "react"; import '../css/components/UserControls.css'; import { useLoginContext } from "../structures/UserContext"; +import ClickDetector from "../util/ClickDetector"; +import { clearSession, post } from "../util/Util"; const UserControls = () => { - const [user] = useLoginContext(); + const [user, updateUser] = useLoginContext(); + const detailsRef = useRef(); if (!user) return; - return
- - Hello {user.displayName} - - -
-

Profile

-
-

Logout

-
-
; + const logOut = async () => { + const response = await post('/api/logout'); + if (response.status === 200) { + clearSession(); + updateUser(); + } + }; + + return { + if (detailsRef.current) detailsRef.current.removeAttribute('open'); + }}> +
+ + Hello {user.displayName} + + + +
+

Profile

+
+

Logout

+
+ +
+
; }; diff --git a/src/util/ClickDetector.js b/src/util/ClickDetector.js new file mode 100644 index 0000000..8f5b351 --- /dev/null +++ b/src/util/ClickDetector.js @@ -0,0 +1,35 @@ +import React, { useEffect, useRef } from "react"; + +const alerter = (ref, callback) => { + useEffect(() => { + + const listener = (event) => { + if (ref.current && !ref.current.contains(event.target)) { + return callback(); + } + }; + + document.addEventListener('mousedown', listener); + + return () => { + document.removeEventListener('mousedown', listener); + }; + + }, [ref]); +}; + +// Component wrapper to enable listening for clicks outside of the given component +const ClickDetector = ({ children, callback }) => { + + const wrapperRef = useRef(null); + alerter(wrapperRef, callback); + + return ( +
+ {children} +
+ ); + +}; + +export default ClickDetector; \ No newline at end of file