Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save washingtonsoares/b6d6330c6aa498809113c5632865132d to your computer and use it in GitHub Desktop.
Save washingtonsoares/b6d6330c6aa498809113c5632865132d to your computer and use it in GitHub Desktop.
// https://letsbuildui.dev/articles/building-a-dropdown-menu-component-with-react-hooks
import { useState, useEffect, RefObject } from 'react';
export const useDetectOutsideClick = (ref: RefObject<HTMLElement>, initialState: boolean) => {
const [isActive, setIsActive] = useState(initialState);
useEffect(() => {
const pageClickEvent = (event: MouseEvent) => {
// If the active element exists and is clicked outside of
if (ref.current !== null && !ref.current.contains(event.target as Node)) {
setIsActive(!isActive);
}
};
// If the item is active (ie open) then listen for clicks
if (isActive) {
window.addEventListener('click', pageClickEvent);
}
return () => {
window.removeEventListener('click', pageClickEvent);
};
}, [isActive, ref]);
return [isActive, setIsActive] as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment