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.
<Menu as="div" className="relative inline-block text-left "> <div> <Menu.Button className="inline-flex w-full justify-center rounded-md bg-white px-4 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:outline-none focus:ring-offset-gray-100"> Features <ChevronDownIcon className="-mr-1 ml- h-5 w-5" aria-hidden="true" /> </Menu.Button> </div> <Transition as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items className="absolute left-0 z-10 mt-2 w-56 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"> <div className="py-1"> <Menu.Item> {({ active }) => ( <Link to="#" className={classNames( active ? "bg-primary-light-bk text-gray-900" : "text-gray-500", "block px-4 py-2 text-sm" )} > Feature 1 </Link> )} </Menu.Item> <Menu.Item> {({ active }) => ( <Link to="#" className={classNames( active ? "bg-primary-light-bk text-gray-900" : "text-gray-500", "block px-4 py-2 text-sm" )} > Feature 2 </Link> )} </Menu.Item> </div> </Menu.Items> </Transition> </Menu>
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.
<Menu.Button onMouseEnter={({target})=> target.click()} className="..."> Features <ChevronDownIcon className="-mr-1 ml- h-5 w-5" aria-hidden="true" /> </Menu.Button>
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!
<Menu as="div" className="relative inline-block text-left "> {({open}) => ( <div> <div> <Menu.Button onMouseEnter={({target})=> open ? "" : target.click()} className="inline-flex w-full justify-center rounded-md bg-white px-4 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:outline-none focus:ring-offset-gray-100"> Features <ChevronDownIcon className="-mr-1 ml- h-5 w-5" aria-hidden="true" /> </Menu.Button> </div> ... your code ... </div> )} </Menu>