From 8fb1cd3889be557a00dffe09ac3428bcd2949167 Mon Sep 17 00:00:00 2001 From: Robin van Zanten Date: Thu, 22 Jul 2021 17:20:42 +0200 Subject: [PATCH] feat(project): add detect outsideclick component --- .../DetectOutsideClick/DetectOutsideClick.tsx | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/components/DetectOutsideClick/DetectOutsideClick.tsx diff --git a/src/components/DetectOutsideClick/DetectOutsideClick.tsx b/src/components/DetectOutsideClick/DetectOutsideClick.tsx new file mode 100644 index 000000000..0b22bbd53 --- /dev/null +++ b/src/components/DetectOutsideClick/DetectOutsideClick.tsx @@ -0,0 +1,32 @@ +import React, { useEffect, RefObject } from 'react'; + +type Prop = { + el?: RefObject; + callback: () => void; + isActive: boolean; + children: React.ReactNode; +}; + +const DetectOutsideClick = ({ el, callback, isActive, children }: Prop) => { + useEffect(() => { + const onClick = (event: MouseEvent) => { + // If the active element exists and is clicked outside of + if (isActive && el?.current !== null && !el?.current?.contains(event.target as Node)) { + callback(); + } + }; + + // If the item is active (ie open) then listen for clicks outside + if (isActive) { + setTimeout(() => window.addEventListener('click', onClick), 0); + } + + return () => { + window.removeEventListener('click', onClick); + }; + }, [isActive, el, callback]); + + return {children}; +}; + +export default DetectOutsideClick;