Skip to content

Commit

Permalink
Use context to use same slot for submenu portal
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed May 29, 2023
1 parent 49416a6 commit e492792
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions packages/components/src/dropdown-menu-v2/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
/**
* WordPress dependencies
*/
import { forwardRef } from '@wordpress/element';
import { forwardRef, createContext, useContext } from '@wordpress/element';
import { isRTL } from '@wordpress/i18n';
import { check, chevronRightSmall, lineSolid } from '@wordpress/icons';
import { SVG, Circle } from '@wordpress/primitives';
Expand Down Expand Up @@ -35,6 +35,12 @@ const SUB_MENU_OFFSET_SIDE = 12;
// Opposite amount of the top padding of the menu item
const SUB_MENU_OFFSET_ALIGN = -8;

const DropdownMenuPrivateContext = createContext< {
portalContainer: HTMLElement | null;
} >( {
portalContainer: null,
} );

/**
* `DropdownMenu` displays a menu to the user (such as a set of actions
* or functions) triggered by a button.
Expand Down Expand Up @@ -77,7 +83,11 @@ export const DropdownMenu = ( {
alignOffset={ alignOffset }
loop={ true }
>
{ children }
<DropdownMenuPrivateContext.Provider
value={ { portalContainer: slot.ref?.current } }
>
{ children }
</DropdownMenuPrivateContext.Provider>
</DropdownMenuStyled.Content>
</DropdownMenuPrimitive.Portal>
</DropdownMenuPrimitive.Root>
Expand Down Expand Up @@ -123,6 +133,8 @@ export const DropdownSubMenu = ( {
children,
trigger,
}: DropdownSubMenuProps ) => {
const { portalContainer } = useContext( DropdownMenuPrivateContext );

return (
<DropdownMenuPrimitive.Sub
defaultOpen={ defaultOpen }
Expand All @@ -135,7 +147,7 @@ export const DropdownSubMenu = ( {
>
{ trigger }
</DropdownMenuStyled.SubTrigger>
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Portal container={ portalContainer }>
<DropdownMenuStyled.SubContent
loop
sideOffset={ SUB_MENU_OFFSET_SIDE }
Expand Down

0 comments on commit e492792

Please sign in to comment.