ProfileDropdown: dismiss when clicked outside

gleasonator
Alex Gleason 2023-02-06 16:53:56 -06:00
rodzic 7f6b19aa4a
commit 53a930c75c
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
1 zmienionych plików z 21 dodań i 1 usunięć

Wyświetl plik

@ -42,7 +42,7 @@ const ProfileDropdown: React.FC<IProfileDropdown> = ({ account, children }) => {
const intl = useIntl();
const [visible, setVisible] = useState(false);
const { x, y, strategy, refs } = useFloating({ placement: 'bottom-end' });
const { x, y, strategy, refs } = useFloating<HTMLButtonElement>({ placement: 'bottom-end' });
const authUsers = useAppSelector((state) => state.auth.users);
const otherAccounts = useAppSelector((state) => authUsers.map((authUser: any) => getAccount(state, authUser.id)!));
@ -102,10 +102,30 @@ const ProfileDropdown: React.FC<IProfileDropdown> = ({ account, children }) => {
const toggleVisible = () => setVisible(!visible);
const handleWindowClick = (e: MouseEvent) => {
if (e.target) {
const clickWithin = [
refs.floating.current?.contains(e.target as Node),
(refs.reference.current as HTMLButtonElement | undefined)?.contains(e.target as Node),
].some(Boolean);
if (!clickWithin) {
setVisible(false);
}
}
};
useEffect(() => {
fetchOwnAccountThrottled();
}, [account, authUsers]);
useEffect(() => {
window.addEventListener('click', handleWindowClick);
return () => {
window.removeEventListener('click', handleWindowClick);
};
}, []);
return (
<>
<button type='button' ref={refs.setReference} onClick={toggleVisible}>