Skip to content

Commit

Permalink
feat(project): add detect outsideclick component
Browse files Browse the repository at this point in the history
  • Loading branch information
RCVZ committed Jul 22, 2021
1 parent 9b92e2d commit 8fb1cd3
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/components/DetectOutsideClick/DetectOutsideClick.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React, { useEffect, RefObject } from 'react';

type Prop = {
el?: RefObject<HTMLDivElement>;
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 <React.Fragment>{children}</React.Fragment>;
};

export default DetectOutsideClick;

0 comments on commit 8fb1cd3

Please sign in to comment.