Published on

React tips: Independent Control for Multiple Dropdown Menus

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Independent Control for Multiple Dropdown Menus in React

1. Added an openMenus state object

This object uses the document ID as the key to track the open/close state of each dropdown menu.

2. Modified DropdownMenu’s open and onOpenChange properties

These properties now use the specific document ID to manage the state for each dropdown menu.

3. Updated the RemoveDialog’s onCancel callback

This ensures that only the corresponding dropdown menu is closed when cancelling an action.

const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({});

...
return {documents?.map((document: DocumentData) => (
  <TableRow key={document.id}>
  <DropdownMenu
    open={openMenus[document.id]}
    onOpenChange={(open) =>
      setOpenMenus((prev) => ({
        ...prev,
        [document.id]: open,
      }))
    }
  >
    ...
    <DropdownMenuContent>
      <DropdownMenuItem
        onClick={(e) => e.preventDefault()}
        className="cursor-pointer"
      >
        <RemoveDialog
          onConfirm={() => handleDeleteDocument(document.id)}
          onCancel={() =>
            setOpenMenus((prev) => ({
              ...prev,
              [document.id]: false,
            }))
          }
        />
      </DropdownMenuItem>
    </DropdownMenuContent>
    ...
))}
...