Skip to content

Commit

Permalink
fix: close the options menu if clicking on trigger
Browse files Browse the repository at this point in the history
  • Loading branch information
anastasialanz committed Oct 3, 2024
1 parent 952d674 commit bd25a61
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ test('should toggle menu on trigger clicks', async () => {
</OptionsMenu>
);

const button = screen.getByRole('button');
const button = screen.getByRole('button', { name: 'trigger' });

await user.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
Expand Down
3 changes: 2 additions & 1 deletion packages/react/src/components/OptionsMenu/OptionsMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useRef, useCallback } from 'react';
import React, { useState, useRef } from 'react';
import OptionsMenuWrapper from './OptionsMenuWrapper';
import OptionsMenuList from './OptionsMenuList';
import setRef from '../../utils/setRef';
Expand Down Expand Up @@ -73,6 +73,7 @@ const OptionsMenu = ({
onKeyDown: handleTriggerKeyDown
})}
<OptionsMenuList
triggerRef={triggerRef}
show={show}
menuRef={(el) => {
if (menuRef) {
Expand Down
7 changes: 7 additions & 0 deletions packages/react/src/components/OptionsMenu/OptionsMenuList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ const [up, down, tab, enter, space, esc] = [38, 40, 9, 13, 32, 27];
export interface OptionsMenuListProps
extends Omit<OptionsMenuProps, 'trigger'> {
className?: string;
triggerRef: React.RefObject<HTMLButtonElement>;
}

const OptionsMenuList = ({
children,
menuRef,
show,
className,
triggerRef,
onClose = () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
onSelect = () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
closeOnSelect = true,
Expand Down Expand Up @@ -96,6 +98,11 @@ const OptionsMenuList = ({
};

const handleClickOutside = (e: MouseEvent | TouchEvent) => {
const target = e.target as Node;
const triggerElement = triggerRef.current;
if (target === triggerElement || triggerElement?.contains(target)) {
return;
}
if (show) {
onClose();
}
Expand Down

0 comments on commit bd25a61

Please sign in to comment.