Skip to content

Instantly share code, notes, and snippets.

@jmblog
Created December 29, 2020 05:47
Show Gist options
  • Save jmblog/fb05eaba27a8993749145adc898f9bcb to your computer and use it in GitHub Desktop.
Save jmblog/fb05eaba27a8993749145adc898f9bcb 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;
};
@SauloOliveira06
Copy link

The best outside click, no bugs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment