Chakra-UI


Menu

|

Chakra Docs

|

Unleashing the Potential of Chakra UI's Menu Component: Dropdown menus are a common design pattern that adds functionality and interactivity to websites. If you're seeking an accessible and feature-rich solution to implement this pattern, look no further than Chakra UI's Menu component. With its focus management capabilities and versatile options, Chakra UI empowers you to create seamless and user-friendly menus.

The Menu component in Chakra UI serves as a wrapper, providing essential context, state, and focus management for your menus. It acts as a central hub, facilitating the smooth operation of various menu-related elements. But the power of Chakra UI extends beyond the Menu component alone. Let's explore the components that complement and enhance its functionality:

  • MenuList: This component serves as a container for your menu items. It ensures proper structuring and organization of your menu content. Remember, the MenuList should always be a direct child of the Menu component.
  • MenuButton: Acting as the trigger for the menu list, the MenuButton handles the opening and closing of the menu when interacted with. It simplifies the user experience by providing a clear way to access the menu items.
  • MenuItem: As a direct child of the MenuList, the MenuItem component handles the selection logic for your menu. It allows users to interact with the menu items effortlessly, making their navigation more intuitive.
  • MenuGroup: If you have related menu items that need to be grouped together, the MenuGroup component comes in handy. It enables you to organize and categorize your menu options, improving the overall user experience.
  • MenuDivider: Visual separators play a crucial role in menu design, enhancing clarity and structure. The MenuDivider component allows you to create visually appealing menus by adding clear distinctions between items and groups.
  • MenuOptionGroup: For menus with checkable items like radio buttons or checkboxes, the MenuOptionGroup component simplifies the process. It provides a wrapper to group and manage these selectable options, making it easier for users to make their choices.
  • MenuItemOption: This component works in conjunction with the MenuOptionGroup, providing the checkable menu item functionality. It allows users to make selections within the menu, creating a cohesive and interactive experience.

Chakra UI's Menu component, along with its complementary components, offers a comprehensive set of tools to elevate your website's menu design. Furthermore, Chakra UI's theming capabilities ensure that your menus seamlessly integrate with your overall design aesthetic.

These components can be imported as follows:

Examples

Basic Menu


⦾ In this example, we have a Menu component wrapping the menu-related elements. The MenuButton component serves as the trigger button for the dropdown menu. It is rendered as a Button component with a chevron icon indicating that it expands the menu when clicked. The text "Things to Do:" is displayed as the button's content.

The MenuList component represents the container for the menu items. It is where you define and render individual MenuItem components. In this example, we have four menu items: "Get Coffee," "Take a Walk," "Pet a Dog," and "Meditate."

Code

Accessing Internal State


⦾ To access the internal state of the Menu component in Chakra UI, you can utilize a render prop function as children. This approach grants you access to the internal state properties, such as isOpen, and theonClose method.

In this example, instead of directly placing child components within the Menu component, we provide a render prop function as the children. This function receives an object with the isOpen property, which indicates whether the menu is currently open or closed.

Using this isOpen property, we can dynamically update the appearance of the MenuButton component by setting the isActive prop based on the isOpen value. This allows us to style the button differently depending on the menu state.

The render prop function also enables us to customize the content of the MenuButton. In this case, we display "Close" or "Open" text based on the current state. This text is rendered dynamically by utilizing a ternary operator to conditionally display the appropriate label.

Within the render prop function, we continue defining the MenuListcomponent and its child MenuItem components. These represent the dropdown menu items that will be displayed when the menu is open. In this example, we have two menu items: "Do Something" and "Do Something Better," with the latter having a click event handler that triggers an alert when clicked.

By leveraging the render prop function in the Menu component, you can gain more control over the internal state and behavior of the menu, allowing for dynamic rendering and seamless interaction within your application.

Code

Customizing the Menu Button


⦾ In this example, we have a menu with a custom button component using Chakra UI's Menu component. The custom button component, CustomButton, is created using the forwardRef function. This function allows the ref to be passed to the underlying DOM button element, ensuring proper positioning of the MenuList.

By utilizing the custom button component with the Menu component, we can create a customized menu trigger with the desired visual appearance and behavior. The menu will now open and close as expected without any type errors.

Code

Letter Navigation Menu


⦾ This example is a customized menu component that allows you to navigate through menu items by typing a letter key. When the focus is on the MenuButton or within the MenuList, typing a letter will initiate a search and move the focus to the first MenuItem that starts with the typed letter.

To use the letter navigation functionality, follow these steps. You will notice that the focus automatically moves to the first MenuItem that begins with the letter you typed.

  1. Open the menu by clicking on the MenuButton.
  2. Try typing any letter (for example, "U") on your keyboard.

Code

Image Menu


⦾ An image menu is a versatile component that allows you to create visually appealing menus with custom images. By leveraging this functionality, you can enhance the user experience by presenting menu options accompanied by relevant and eye-catching images. Whether used in e-commerce websites to showcase product options, travel platforms to display destination choices, or recipe applications to present mouth-watering dishes, the images add an engaging visual element that captures users' attention and helps them make informed selections. Its flexibility makes it suitable for a wide range of applications, enabling you to create unique and captivating menus tailored to your specific needs.

This image menu example is a unique menu component that showcases different images of the renowned actor, Keanu Reeves. Each menu item features a custom image of Keanu Reeves along with a corresponding label.

Inside the MenuList, we have three MenuItem components, each showcasing a different image of Keanu Reeves. The images are fetched from the "placekeanu.com" website with varying URLs to display unique images. Alongside each image, there is a label denoting the specific Keanu Reeves version.

Code

Icon and Command Enhancement


⦾ Incorporating icons and commands into menus can significantly enhance the user experience and streamline interactions. The following example demonstrates how to add icons and commands to menu items using the Chakra UI Menu component.

In this customized example, we utilize the Chakra UI Menu component to create a menu with enhanced functionality. The MenuButton, rendered as an IconButton, features the HamburgerIcon and serves as the trigger for the menu. Within the MenuList, we define several MenuItem components. Each MenuItem includes an icon representing the action associated with it, such as AddIcon, ExternalLinkIcon, RepeatIcon, and EditIcon.

Additionally, a command or hotkey is specified for each menu item using the command prop, which provides a convenient way to communicate keyboard shortcuts or commands to the user. By incorporating icons and commands, this menu provides clear visual cues and helps users quickly identify and access specific actions. This approach can be adapted for a variety of use cases, such as productivity tools, text editors, or any application where efficient menu navigation and command execution are essential.

Whaddamenu!

Code

MenuGroup


⦾ The MenuGroup component in Chakra UI offers a convenient way to organize related menu items and improve menu navigation. By grouping menu items under specific titles, you can create a more structured and user-friendly menu experience. In this example, we have a menu centered around a Likes and Dislikes theme. TheMenuButton, styled as a Button with the 'pink' color scheme.

Within the MenuList, we utilize the MenuGroup component to create two distinct groups: Likes and Dislikes. Each group is defined by a title passed as a prop to MenuGroup. Under the Likes group, we have menu items like "Coffee" and "Dark Chocolate." After a MenuDivider, the Dislikes group includes menu items such as "Chicken Liver" and "Mean People."

By employing the MenuGroup component, you can structure your menus in a logical manner, making it easier for users to locate and select the desired options. This approach is particularly useful when organizing complex menus with multiple categories or sections. The MenuGroup component ensures a cohesive and intuitive user experience when navigating through various menu items.

Code

MenuItem as a Link


⦾ In certain scenarios, you may want to render a MenuItem as a link to provide interactive navigation within your menu. By utilizing the as and href attributes, you can easily achieve this functionality.

By incorporating this approach, users can click on the menu items and navigate to the specified URLs or anchor targets. This is particularly useful when building navigation menus or dropdowns that require clickable links as menu options.

Code

Additional functionality


  • Lazy Mounting of Menu Items: YBy default, the Menu component in Chakra UI renders all children of the MenuList to the DOM, even if they are not visible. However, there might be situations where you want to defer the rendering of each menu item until the menu is actually opened. To achieve this, you can utilize the isLazy prop. This feature is particularly useful if you aim to optimize the performance of your Menu or if you need to make network calls or perform certain actions on mount that should only occur when the menu is displayed to the user.
  • Rendering Menu in a Portal: To achieve greater flexibility and control over the placement and behavior of menus, Chakra UI provides the option to render menus in a portal. This is accomplished by importing the Portal component and wrapping the MenuList within it. Let's explore the benefits and use cases of rendering menus in a portal.

    By utilizing a portal, you gain the ability to render the menu outside of its parent component's DOM hierarchy. This allows you to control the menu's positioning and ensure it appears exactly where desired, even in complex layouts or nested components. It provides greater control over z-index stacking and avoids potential overflow or clipping issues that may occur within parent components.

    This can be implemented simply by wrapping the MenuList component inside of a Portal component.

  • Sorting and Filtering with Menu Option Groups: In Chakra UI, you have the ability to compose a menu for table headers that facilitates sorting and filtering operations. This can be achieved by utilizing the MenuOptionGroup and MenuItemOption components. Let's explore how to leverage these components to create dynamic and interactive menu option groups.

    The MenuOptionGroup component allows you to group related menu options together. It acts as a wrapper for the MenuItemOption components, which represent individual options within the group. This approach is particularly useful when dealing with table headers that require sorting or filtering capabilities.

    The following shows how to implement this functionality:

    Code

Did you know?

Creative Idea No. 1

Chakra UI's Menu component can be integrated seamlessly with form controls. By utilizing the useDisclosure hook from Chakra UI, you can create a menu that functions as a custom dropdown select component. Let's consider an example where we use a Menu to pick a fruit from a list and show the chosen fruit in a text box.

Code

Creative Idea No. 2

Custom Menu Divider: In Chakra UI, you have the flexibility to style the MenuDivider to fit your design. You can change its color, thickness, margin, or add any other CSS properties. You can use the _focus property to change its color when it receives focus. In the following example, the color of the MenuDivider is set to purple.500, its thickness is set to 2px, and the margin is set to 10px on top and bottom.

Code

Creative Idea No. 3

Split Button Dropdown Menu: This example is a variation of a split button, which is essentially a button with a default action, and an attached list of alternatives. The main button (the one on the left) displays the current action (initially 'Default Action'), and it performs this action when clicked. The smaller button (the one on the right with the chevron icon) opens a dropdown menu with alternative actions.
This saves space by grouping related actions in a compact UI component, making it beneficial for limited screen real estate. Additionally, it enables the dynamic updating of the default action based on the user's selection from the dropdown menu, allowing for efficient repetition of the most recent action.

Code

copyright © 2023 IHeartComponents | evanmarie.com

Chakra-UIRemix

Special thanks to Stefan Bohacek / Generative Placeholders.