From 71904a185c9378d38c89565cd2e16ed238504fff Mon Sep 17 00:00:00 2001 From: Jeevan Jyoti Dash Date: Sun, 16 Jan 2022 00:29:13 +0530 Subject: [PATCH] Issue fix for the menu has no menu items #1223 (#1279) * fix issue #1223 * fix empty menu items without useState --- docs/documentation/components/menu.mdx | 10 +++++++-- src/menu/src/Menu.js | 30 ++++++++++++-------------- src/menu/stories/index.stories.js | 3 +++ 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/docs/documentation/components/menu.mdx b/docs/documentation/components/menu.mdx index 83d54f4e7..d65a60e19 100644 --- a/docs/documentation/components/menu.mdx +++ b/docs/documentation/components/menu.mdx @@ -181,7 +181,7 @@ function MenuOptionsGroupExample() { { label: 'Descending', value: 'desc' }, ]} selected={selectedOrder} - onChange={(selected) => setSelectedOrder(selected)} + onChange={selected => setSelectedOrder(selected)} /> setSelectedField(selected)} + onChange={selected => setSelectedField(selected)} /> ) @@ -237,3 +237,9 @@ The focus styles are currently not working in the docs, sorry for the inconvenie ``` + +## Menu without items + +```jsx + +``` diff --git a/src/menu/src/Menu.js b/src/menu/src/Menu.js index e781ed5f2..a9f38cfc6 100644 --- a/src/menu/src/Menu.js +++ b/src/menu/src/Menu.js @@ -9,6 +9,7 @@ import MenuOptionsGroup from './MenuOptionsGroup' const Menu = memo(function Menu(props) { const menuRef = useRef(null) + const firstItem = useRef() const lastItem = useRef() @@ -16,18 +17,9 @@ const Menu = memo(function Menu(props) { useEffect(() => { const currentMenuRef = menuRef.current - - menuItems.current = currentMenuRef - ? [ - ...currentMenuRef.querySelectorAll( - '[role="menuitemradio"]:not([disabled]), [role="menuitem"]:not([disabled])' - ) - ] - : [] - - if (menuItems.current.length === 0) { - throw new Error('The menu has no menu items') - } + menuItems.current = [ + ...currentMenuRef.querySelectorAll('[role="menuitemradio"]:not([disabled]), [role="menuitem"]:not([disabled])') + ] firstItem.current = menuItems.current[0] lastItem.current = menuItems.current[menuItems.current.length - 1] @@ -68,9 +60,7 @@ const Menu = memo(function Menu(props) { const { target } = e const menuItem = menuItems.current && menuItems.current.find(item => item === target) - if (!menuItem) { - return - } + if (!menuItem) return if (e.key === 'ArrowDown') { e.preventDefault() @@ -101,9 +91,17 @@ const Menu = memo(function Menu(props) { }, [menuRef]) const { children } = props + + const renderEmptyChildren = () => { + return ( + + No items... + + ) + } return ( - {children} + {children || renderEmptyChildren()} ) }) diff --git a/src/menu/stories/index.stories.js b/src/menu/stories/index.stories.js index d09ccd617..7ec050495 100644 --- a/src/menu/stories/index.stories.js +++ b/src/menu/stories/index.stories.js @@ -195,6 +195,9 @@ storiesOf('menu', module) > + }> + + Arrow down on a button will bring focus inside the popover.