Search code examples
javascriptcssreactjsnext.jschakra-ui

Is there a way to make chakra ui MenuList items always visible


I am using Chakra UI to create a menu. I have something like this:

<Menu>
    <MenuButton>hover over this</MenuButton>

    <MenuList>
        <Flex>To show/hide this</Flex> 
    </MenuList>
</Menu>

I am trying to dynamically open the tag on hover. The MenuList default is to open on user click. When I click on the button and then hover over it, my hover state works. I am trying to figure out a way so that the user does not have to click on the MenuButton for hovering over it to work.


Solution

  • Adding on to Bassem's answer. We can add onMouseEnter and onMouseLeave to the menu list so that it doesn't close when we leave the button.

    import React from "react";
    import {
      Flex,
      MenuItem,
      Menu,
      MenuButton,
      MenuList,
      Button,
      useDisclosure
    } from "@chakra-ui/react";
    
    export default function App() {
      const { isOpen, onOpen, onClose } = useDisclosure();
      return (
        <div className="App">
          <Flex height="100vh" align="center" justifyContent="center" bg="gray.100">
            <Menu isOpen={isOpen}>
              <MenuButton
                as={Button}
                variant="solid"
                colorScheme="teal"
                onMouseEnter={onOpen}
                onMouseLeave={onClose}
              >
                Hover Me
              </MenuButton>
              <MenuList onMouseEnter={onOpen} onMouseLeave={onClose}>
                <MenuItem>Download</MenuItem>
                <MenuItem>Create a Copy</MenuItem>
                <MenuItem>Mark as Draft</MenuItem>
                <MenuItem>Delete</MenuItem>
                <MenuItem>Attend a Workshop</MenuItem>
              </MenuList>
            </Menu>
          </Flex>
        </div>
      );
    }
    

    You can read more here https://www.coffeeclass.io/snippets/use-disclosure-menu-chakra-ui