ui: Unable to use Dialog inside a DropdownMenu ( with DialogTrigger or without it )

I’m having an issue with triggering a dropdown menu correctly. The dropdown menu contains a dialog, and I’m trying to trigger the dropdown using a DropdownMenuTrigger or a DialogTrigger, but neither is working as expected.

Minimal Reproducible Example:


<DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button className="bg-gray-800 text-white mb-4 h-12 w-full text-md pr-4 text-left">
                                                    Create Campaign
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="center" className="w-[260px] bg-white p-4">
                                                <Dialog>
                                                    <DialogTrigger asChild>
                                                        <DropdownMenuItem className="text-md pt-2">
                                                            trigger dialog from DropdownMenuItem
                                                        </DropdownMenuItem>
                                                    </DialogTrigger>
                                                    <DialogContent className="text-black max-w-[60%] bg-white p-6 h-[600px]">
                                                        <div className="flex gap-10 items-start">
                                                            x
                                                        </div>
                                                    </DialogContent>
                                                </Dialog>

                                                <DropdownMenuSeparator className={"bg-gray-300"}/>

                                                <DropdownMenuItem className="text-md pt-3">
                                                    option 2
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 29

Most upvoted comments

If you want to have a DialogBox pop up from a dropdown menu (for example, a dropdown menu to edit a user, which would pop up a DialogBox modal to edit it), you’ll have to do it like this:

<DialogTrigger asChild>
      <DropdownMenuItem onSelect={(e) => e.preventDefault()}>Edit</DropdownMenuItem>
</DialogTrigger>

the key is the preventDefault() call.

@Char99s, @shiftcontrol-dan, Using “preventDefault” works by keeping the dialog open. But it remains open even when the dialog is closed. Is there way to automatically close the dropdown menu when the dialog is closed?

`<DropdownMenu modal={false}> <DropdownMenuTrigger className="hover:bg-violet-200 h-8 w-8 flex justify-center items-center rounded-full"> <IoEllipsisVerticalOutline /> </DropdownMenuTrigger> <DropdownMenuContent className="shadow-md bg-white rounded-sm border p-2"> <AlertDialog> <AlertDialogTrigger asChild> <DropdownMenuItem onSelect={(e) => e.preventDefault()} className=“flex items-center py-1 px-2 rounded-sm hover:!bg-violet-200 cursor-pointer”> <MdDriveFileRenameOutline className="mr-3" /> Rename </DropdownMenuItem> </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>Rename</AlertDialogTitle> <AlertDialogDescription> Please enter a new name for the item: <input type=“text” value={docName} onChange={(e) => { setDocName(e.target.value); }} className=“py-1 px-2 w-full border-2 outline-violet-800 my-2” /> </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel onClick={() => { setDocName(Name); }} className=“hover:text-gray-800 hover:border-violet-500 text-violet-800”> Cancel </AlertDialogCancel> <AlertDialogAction className={ docName == “” ? "bg-gray-200 text-gray-700 hover:bg-gray-200 hover:text-gray-700 cursor-not-allowed " : “” }> Save </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog>

          <AlertDialog>
            <AlertDialogTrigger asChild>
              <DropdownMenuItem
                onSelect={(e) => e.preventDefault()}
                className="flex items-center py-1 px-2 rounded-sm hover:!bg-violet-200 cursor-pointer">
                <MdDeleteForever className="mr-3" />
                Delete
              </DropdownMenuItem>
            </AlertDialogTrigger>
            <AlertDialogContent >
              <AlertDialogHeader>
                <AlertDialogTitle>Delete</AlertDialogTitle>
                <AlertDialogDescription>
                  Are you to delete it permanently ?
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel className="hover:text-gray-800 hover:border-violet-500 text-violet-800">
                  Cancel
                </AlertDialogCancel>
                <AlertDialogAction>Delete</AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </DropdownMenuContent>
      </DropdownMenu>`

Suggestion: Use modal={false} for DropdownMenu to prevent portal rendering issues

The recommended and straightforward solution is to disable modal rendering by setting modal={false} on the DropdownMenu component.

Example Implementation:

<DropdownMenu modal={false}>
  <DropdownMenuTrigger asChild>
    <Button variant="outline" size="icon" className="h-8 w-8">
      <Settings className="h-4 w-4" />
    </Button>
  </DropdownMenuTrigger>
  <DropdownMenuContent align="end">
    <DropdownMenuItem
      onClick={() => {
        setConfirmAction({
          type: "logout",
          name: instance.name,
        });
      }}
      disabled={instance.connectionStatus !== "open"}
    >
      <LogOut className="h-4 w-4 mr-2" />
      Logout
    </DropdownMenuItem>
    <DropdownMenuItem
      onClick={() => {
        setConfirmAction({
          type: "delete",
          name: instance.name,
        });
      }}
      className="text-destructive"
    >
      <Trash2 className="h-4 w-4 mr-2" />
      Delete
    </DropdownMenuItem>
  </DropdownMenuContent>
</DropdownMenu>

Benefits:

Avoids potential z-index/portal-related rendering issues

Maintains all functionality while simplifying DOM structure

Particularly useful in complex layout scenario

ShadCn has provided also some guidance in the Dialog Page - here.

In cases of multiple different dialogs, you would need to tell react which dialog to render

  export function HeaderDropDownMenu() {
    const [dialogMenu, setDialogMenu] = useState<string>("none");
  
    const handleDialogMenu = (): JSX.Element | null => {
      switch (dialogMenu) {
        case "create":
          return <CreateDialog />
        case "delete":
          return <DeleteDialog />;
        default:
          return null;
      }
    };
  
    return (
      <Dialog>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button size="icon" variant="ghost"> Menu </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-56">
            <DropdownMenuGroup>
              <DropdownMenuItem onSelect={() => setDialogMenu("create")}>
                <PlusIcon /> Create Campaign
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => setDialogMenu("delete")}>
                <TrashIcon /> Delete Campaign
              </DropdownMenuItem>
            </DropdownMenuGroup>
          </DropdownMenuContent>
        </DropdownMenu>
        {handleDialogMenu()}
      </Dialog>
    );
 }

And your DeleteDialog should only contain the <DialogContent/> as you’ve already the entire component wrapped in a dialog.

export function DeleteCampaignDialog() {
  return (
    <DialogContent>
      <DialogHeader>
        <DialogTitle>DELETE</DialogTitle>
        <DialogDescription>
          This action cannot be undone. Are you sure you want to permanently
          delete this file from our servers?
        </DialogDescription>
      </DialogHeader>
      <DialogFooter>
        <Button type="submit">Confirm</Button>
      </DialogFooter>
    </DialogContent>
  );
}

I tried a dozen different things, the only way to make it work was to render the dialog outside of the dropdown and handle control manually.

"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { SettingsDialog } from "@/components/settings-dialog"

export default function Home() {
  const [dialogOpen, setDialogOpen] = useState(false)
  const [dropdownOpen, setDropdownOpen] = useState(false)

  // Function to handle opening the dialog and closing the dropdown
  const handleOpenDialog = () => {
    setDropdownOpen(false) // Close the dropdown first
    setTimeout(() => {
      setDialogOpen(true) // Then open the dialog after a small delay
    }, 10)
  }

  return (
    <div className="flex min-h-screen items-center justify-center">
      <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
        <DropdownMenuTrigger asChild>
          <Button variant="outline">Open Menu</Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent>
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuItem>Regular Action</DropdownMenuItem>
          <DropdownMenuItem
            onSelect={(e) => {
              e.preventDefault() // Prevent the dropdown from closing automatically
              handleOpenDialog() // Handle opening the dialog
            }}
          >
            Settings
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* Dialog is rendered outside the dropdown */}
      <SettingsDialog open={dialogOpen} onOpenChange={setDialogOpen} />
    </div>
  )
}

"use client"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

interface SettingsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="sm:max-w-[425px]"
        onPointerDownOutside={(e) => {
          // Prevent closing when clicking inside the dialog
          if (e.target instanceof HTMLElement && e.target.closest('[role="dialog"]')) {
            e.preventDefault()
          }
        }}
      >
        <DialogHeader>
          <DialogTitle>Settings</DialogTitle>
          <DialogDescription>Make changes to your settings here.</DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-4 items-center gap-4">
            <Label htmlFor="name" className="text-right">
              Name
            </Label>
            <Input id="name" defaultValue="John Doe" className="col-span-3" />
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <Label htmlFor="email" className="text-right">
              Email
            </Label>
            <Input id="email" defaultValue="john@example.com" className="col-span-3" />
          </div>
        </div>
        <DialogFooter>
          <Button type="submit">Save changes</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

I correctly set up the dialog rendering based on the state and a switch statement. However, I kept running into an issue where, after closing one dialog, I couldn’t click anywhere else on the page.

It turns out this behavior is related to the following issue: https://github.com/shadcn-ui/ui/issues/1859.

The solution is to update DialogContent like this:

<DialogContent 
  onCloseAutoFocus={(event) => {
    event.preventDefault();
    document.body.style.pointerEvents = '';
  }}
>

Hope this helps anyone else running into the same issue!

The above worked for me, but only after adding DialogTriggers.

export default function Item({ item, itemsCount, folders }: ItemProps) {
  const [dialogMenu, setDialogMenu] = useState<string>('none');

  const handleDialogMenu = (): JSX.Element | null => {
    switch (dialogMenu) {
      case 'rename':
        return <RenameItem id={item.id} name={item.name} />;
      case 'move':
        return (
          <MoveItem
            folderId={item.folder_id}
            currentId={item.id}
            folders={folders}
          />
        );
      case 'delete':
        return <DeleteItem id={item.id} itemsCount={itemsCount} />;
      default:
        return null;
    }
  };

  return (
    <TableRow className="cursor-pointer">
      <ItemInfo item={item} />
      <TableCell>
        <Dialog>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button aria-haspopup="true" size="icon" variant="ghost">
                <MoreHorizontal className="h-4 w-4" />
                <span className="sr-only">Toggle menu</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuGroup>
                <DropdownMenuLabel>Actions</DropdownMenuLabel>
                <DialogTrigger asChild>
                  <DropdownMenuItem
                    onSelect={() => setDialogMenu('rename')}
                    className="cursor-pointer space-x-2"
                  >
                    <FolderPen className="size-3" />
                    <p>Rename</p>
                  </DropdownMenuItem>
                </DialogTrigger>
                <DialogTrigger asChild>
                  <DropdownMenuItem
                    onSelect={() => setDialogMenu('move')}
                    className="cursor-pointer space-x-2"
                  >
                    <Folders className="size-3" />
                    <p>Move</p>
                  </DropdownMenuItem>
                </DialogTrigger>
                <DialogTrigger asChild>
                  <DropdownMenuItem
                    onSelect={() => setDialogMenu('delete')}
                    className="cursor-pointer space-x-2"
                  >
                    <Trash className="size-3" />
                    <p>Delete</p>
                  </DropdownMenuItem>
                </DialogTrigger>
              </DropdownMenuGroup>
            </DropdownMenuContent>
          </DropdownMenu>
          {handleDialogMenu()}
        </Dialog>
      </TableCell>
    </TableRow>
  );
}

I like to extract the open-state handling into a useDialog hook and pass the props returned from that hook to the dialog.

useDialog hook

import { useCallback, useState } from "react";

export function useDialog() {
  const [open, onOpenChange] = useState(false);

  const trigger = useCallback(() => {
    onOpenChange(true);
  }, [onOpenChange]);

  return { props: { open, onOpenChange }, trigger };
}

Example Dialog Component

export default function ExampleDialog({
    dialogProps
}: {
    dialogProps: DialogProps
}) {
  return (
    <Dialog {...dialogProps}> {/* This will contain the open and onOpenChange props */}
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Example Dialog</DialogTitle>
        </DialogHeader>
        {/* Dialog Content */}
      </DialogContent>
    </Dialog>
  );
}

Usage of Dialog and Hook

const exampleDialog = useDialog();

return (
  <>
    <DropdownMenu>
      <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
      <DropdownMenuContent side={side}>
        <DropdownMenuItem onSelect={editDialog.trigger}> {/* pass the trigger function as onSelect */}
          Example Dialog
        </DropdownMenuItem>
        {/* ... Other Dropdown Items ... */}
      </DropdownMenuContent>
    </DropdownMenu>
    <ExampleDialog dialogProps={editDialog.props} /> {/* Pass the returned props from the useDialog hook */}
  </>
);

Well I tried an easier approach, which can make the button looks like dropdown menu item, it will be easy if you want to build up some indepedent components without changing the dropdown menu’s structure.

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Trash2 } from "lucide-react";

export default function DeleteButton() {
  return (
    <DropdownMenuItem asChild>
      <AlertDialog>
        <AlertDialogTrigger asChild>
          {/* To make a button looks like dropdown menu item */}
          <Button
            size="sm"
            variant="ghost"
            className="w-full flex items-center justify-start gap-2 px-2 py-1.5 text-sm"
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Delete User
          </Button>
          {/* Show Dialog */}
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete your
              account and remove your data from our servers.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction>Continue</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </DropdownMenuItem>
  );
}

@ReneNieto, I had the same issue but with the Dialog component. The reason behind it was that on there was the class pointer-events: none. You will need to handle its open state separately.

thank you so much, that actually worked, I had to assign a separate state to the dropdown menu and add set false on both states when closing the modal.

So I have tinkered with the code. trying every possible solutions posted here, but I still can’t get the modal nor dropdown menu to work.

I am using react-router + vite framework. The issue was i was using the fetcher from useFetcher hook in the alertdialog component i made thats imported into dropdown menu.

removing all the fetchers, made it work.

Wrap your DropdownMenu in a Dialog component, and the DialogTrigger should be a child of the DropdownMenuItem with the asChild prop.

<Dialog>
  <DropdownMenu>
    <DropdownMenuTrigger>
      <Button>Menu</Button>
    </DropdownMenuTrigger>
    <DropdownMenuContent>
    <DropdownMenuItem>Foo bar</DropdownMenuItem>
    <DropdownMenuItem asChild> 
      <DialogTrigger>Modal</DialogTrigger>
    </DropdownMenuItem>
  </DropdownMenu>
 
  <DialogContent>Hello world</DialogContent>
</Dialog>

If you want to have a DialogBox pop up from a dropdown menu (for example, a dropdown menu to edit a user, which would pop up a DialogBox modal to edit it), you’ll have to do it like this:

<DialogTrigger asChild>
      <DropdownMenuItem onSelect={(e) => e.preventDefault()}>Edit</DropdownMenuItem>
</DialogTrigger>

the key is the preventDefault() call.

The above solution leaves the Dropdown menu open, even after the dialog has been closed. Placing the Dropdown within the Dialog is a better solution. This works well for me:

<Dialog>
  <DropdownMenu>
    <DropdownMenuTrigger>
      <KebabMenuIcon />
    </DropdownMenuTrigger>
    <DropdownMenuContent>
      <DropdownMenuItem asChild>
        <Button>
          Save
          <BookmarkIcon />
        </Button>
      </DropdownMenuItem>
      <DropdownMenuSeparator />
      <DropdownMenuItem>
        <DialogTrigger asChild>
          <Button>
            Delete
            <DeleteIcon />
          </Button>
        </DialogTrigger>
      </DropdownMenuItem>
    </DropdownMenuContent>
  </DropdownMenu>
  <DeleteDialogContent />
</Dialog>