Skip to content

Commit

Permalink
feat(useContextMenu): add ref support (#13210)
Browse files Browse the repository at this point in the history
* feat(useContextMenu): add support for react refs as trigger

* fix(menu): reset position when closed to prevent flickering

---------

Co-authored-by: Francine Lucca <40550942+francinelucca@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
3 people committed Feb 23, 2023
1 parent dba4de9 commit f32a1b3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
14 changes: 8 additions & 6 deletions packages/react/src/components/ContextMenu/useContextMenu.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';

/**
* @param {Element|Document|Window} [trigger=document] The element which should trigger the Menu on right-click
* @param {Element|Document|Window|object} [trigger=document] The element or ref which should trigger the Menu on right-click
* @returns {object} Props object to pass onto Menu component
*/
function useContextMenu(trigger = document) {
Expand All @@ -22,15 +22,17 @@ function useContextMenu(trigger = document) {
}

useEffect(() => {
const el = trigger?.current ?? trigger;

if (
(trigger && trigger instanceof Element) ||
trigger instanceof Document ||
trigger instanceof Window
(el && el instanceof Element) ||
el instanceof Document ||
el instanceof Window
) {
trigger.addEventListener('contextmenu', openContextMenu);
el.addEventListener('contextmenu', openContextMenu);

return () => {
trigger.removeEventListener('contextmenu', openContextMenu);
el.removeEventListener('contextmenu', openContextMenu);
};
}
}, [trigger]);
Expand Down
4 changes: 4 additions & 0 deletions packages/react/src/components/Menu/Menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,10 @@ const Menu = React.forwardRef(function Menu(
useEffect(() => {
if (open) {
handleOpen();
} else {
// reset position when menu is closed in order for the --shown
// modifier to be applied correctly
setPosition(-1, -1);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
Expand Down

0 comments on commit f32a1b3

Please sign in to comment.