Skip to content

Commit

Permalink
fix: Menu Drop down (#1342)
Browse files Browse the repository at this point in the history
Close the new USWDS page header dropdown when clicking outside of it
[#1296](#1296)

### Validation / Testing
Open one of the two drop down options, click on another link on the
page. When the browser navigates to the new page that original dropdown
menu should be closed.
  • Loading branch information
snmln authored Dec 20, 2024
2 parents c62a0d5 + 5acc803 commit f39df50
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React from 'react';
import React, { useCallback } from 'react';
import { USWDSNavDropDownButton } from '../../uswds/header/nav-drop-down-button';
import { USWDSMenu } from '../../uswds/header/menu';
import { DropdownNavLink } from '../types';
import { createDynamicNavMenuList } from './create-dynamic-nav-menu-list';
import { SetState } from '$types/aliases';
import { LinkProperties } from '$types/veda';
import { useClickOutside } from '$utils/use-click-outside';

interface NavDropDownButtonProps {
item: DropdownNavLink;
Expand Down Expand Up @@ -32,11 +33,20 @@ export const NavDropDownButton = ({
return newIsOpen;
});
};

const handleClickOutside = useCallback(() => {
if (isOpen[index]) {
setIsOpen((prevIsOpen) => {
const newIsOpen = [...prevIsOpen];
newIsOpen[index] = false;
return newIsOpen;
});
}
}, [index, isOpen, setIsOpen]);
const dropdownRef = useClickOutside(handleClickOutside);
const submenuItems = createDynamicNavMenuList(item.children, linkProperties);

return (
<React.Fragment key={item.id}>
<div key={item.id} ref={dropdownRef}>
<USWDSNavDropDownButton
onToggle={() => onToggle(index, setIsOpen)}
menuId={item.title}
Expand All @@ -48,6 +58,6 @@ export const NavDropDownButton = ({
isOpen={isOpen[index]}
id={`${item.id}-dropdown`}
/>
</React.Fragment>
</div>
);
};
15 changes: 15 additions & 0 deletions app/scripts/utils/use-click-outside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useEffect, useRef } from 'react';
export const useClickOutside = (onClose: () => void) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
onClose();
}
};
document.addEventListener('click', handleClickOutside, true);
return () =>
document.removeEventListener('click', handleClickOutside, true);
}, [onClose]);
return ref;
};

0 comments on commit f39df50

Please sign in to comment.