From 81a8a28b206ee3f805a36decd25fa10666e623c6 Mon Sep 17 00:00:00 2001 From: Joshua T Flowers Date: Wed, 21 Oct 2020 13:01:46 -0400 Subject: [PATCH] Only show menu group if items exist (https://github.com/woocommerce/woocommerce-admin/pull/5403) * Only show menu group if items exist * Improve performance for menu item filtering --- .../navigation/components/container/index.js | 79 +++++++++++-------- 1 file changed, 46 insertions(+), 33 deletions(-) diff --git a/plugins/woocommerce-admin/client/navigation/components/container/index.js b/plugins/woocommerce-admin/client/navigation/components/container/index.js index 9d2754cbff1..233e6945f1e 100644 --- a/plugins/woocommerce-admin/client/navigation/components/container/index.js +++ b/plugins/woocommerce-admin/client/navigation/components/container/index.js @@ -2,7 +2,7 @@ * External dependencies */ import { __ } from '@wordpress/i18n'; -import { useEffect, useState } from '@wordpress/element'; +import { useEffect, useMemo, useState } from '@wordpress/element'; import { compose } from '@wordpress/compose'; import { __experimentalNavigation as Navigation, @@ -62,6 +62,22 @@ const Container = ( { menuItems } ) => { return removeListener; }, [ menuItems ] ); + const getMenuItemsByCategory = ( items ) => { + return items.reduce( ( acc, item ) => { + if ( ! acc[ item.parent ] ) { + acc[ item.parent ] = [ [], [] ]; + } + const index = item.menuId !== 'secondary' ? 0 : 1; + acc[ item.parent ][ index ].push( item ); + return acc; + }, {} ); + }; + + const categorizedItems = useMemo( + () => getMenuItemsByCategory( menuItems ), + [ menuItems ] + ); + return (
@@ -80,38 +96,35 @@ const Container = ( { menuItems } ) => { ) } > ) } - { categories.map( ( category ) => ( - - - { menuItems - .filter( - ( item ) => - item.parent === category.id && - item.menuId !== 'secondary' - ) - .map( ( item ) => ( - - ) ) } - - - { menuItems - .filter( - ( item ) => - item.parent === category.id && - item.menuId === 'secondary' - ) - .map( ( item ) => ( - - ) ) } - - - ) ) } + { categories.map( ( category ) => { + const [ primaryItems, secondaryItems ] = categorizedItems[ + category.id + ]; + return ( + + { !! primaryItems.length && ( + + { primaryItems.map( ( item ) => ( + + ) ) } + + ) } + { !! secondaryItems.length && ( + + { secondaryItems.map( ( item ) => ( + + ) ) } + + ) } + + ); + } ) }
);