Skip to content
Advertisement

Can’t make the headlessui dropdown to open on mouse hover and not on click

I build an app in React and I have this dropdown from Tailwind UI which is opened on click events and I want to make it open on mouse hover too.

JavaScript

What should I change?

Advertisement

Answer

You’ll need to add onMouseEnter event to your Menu.Button and use handler for this event. Get argument event and then use event.target in handler or { target } and then use just target. then use .click() method that simulates a mouse click on the target element.

When you hover over Menu.Button onMouseEnter has triggered and .click method fires the element’s click event. Menu is opened.

JavaScript

If you try this you’ll see that when you hover the menu.button two times – menu’s opened then closed. That because .click() method fires two times. You can use “open” state. Wrap all of your code inside Menu

{({ open }) => (your code)}

And add onMouseEnter={({target})=> open ? "" : target.click()}. “open” is boolean. True when menu is opened, no need to trigger click event and close it. When “open” is false we’ll use our target.click() method!

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement