Search code examples
reactjsnextuireact-aria

React Aria/ NextUIHow to Activate Dropdown Menu on Hover


How can I actiavte a React Aria / NextUI Dropdown Menu on hover?

This is the Dropdown Menu API: https://nextui.org/docs/components/dropdown#usage which I assume is based on React Aria's Menu https://react-spectrum.adobe.com/react-aria/Menu.html

There are "Trigger" components, but it's unclear how to activate the menu. There is an event fired supposedly onMouseEnter, but then how can I set a variable to activate the menu?

<DropdownTrigger onMouseEnter={}>


Solution

  • Note that this is not in the docs and the docs are wrong for both NextUI and Aria!!! As you can see in the Aria link above, the property is listed in MenuTrigger, but it's actually available in the Menu component...

    Answer

    The Dropdown component has a prop called isOpen which can be passed a boolean to control the state of the menu.

    So you can make a state variable

    const [isOpen, setIsOpen] = useState(false);
    

    And then pass it to the prop. Further you can use the onMouseLeave and onMouseEnter props to control behaviour. Note that these are not documented and that you have to use the onMouseLeave in the Dropdown component and onMouseEnter on the DropdownTrigger component, otherwise the behaviour breaks.

    <Dropdown
              placement="bottom"
              isOpen={isOpen}
              onMouseLeave={() => setIsOpen(false)}
            >
              <DropdownTrigger onMouseEnter={() => setIsOpen(true)}>