DropdownMenu.Item: Handle async functionality onClick #220
-
How would you create an asynchronous menu item? I'm having trouble handling the active state of the dropdown menu: const MyAsyncDropdown = () => {
const [pending, setPending] = useState(false)
return (
<DropdownMenu>
<DropdownMenu.Trigger>
{(attributes) => <Button attributes={attributes}>Open Menu</Button>}
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item
icon={pending ? <Loader /> : undefined}
onClick={async () => {
setPending(true);
await new Promise((resolve) => setTimeout(resolve, 2000));
setPending(false);
// only close menu after promise is resolved
// if error (not shown here) do not close, but toggle error specific props in menu.item
}}
>
Download file
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu>
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey, you can do this with the controlled component behavior. DropdownMenu supports an |
Beta Was this translation helpful? Give feedback.
-
Follow up question: when using the controlled version of a DropdownMenu, how can the onClickOutside behavior be handled? I thought it would be to use the onClose prop, however this is also fired on menu item click so that is not a valid solution in the case of this discussion |
Beta Was this translation helpful? Give feedback.
Hey, you can do this with the controlled component behavior. DropdownMenu supports an
active
flag which you can change after the promise is resolved based on your ownuseState