ProfileDropdown: dismiss when clicked outside
This commit is contained in:
parent
7f6b19aa4a
commit
53a930c75c
|
@ -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}>
|
||||
|
|
Loading…
Reference in New Issue