import React from 'react'; import { MenuToggle, Divider, Dropdown, DropdownGroup, DropdownList, DropdownItem } from '@patternfly/react-core'; export const FavoritesDemo: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState(false); const [favorites, setFavorites] = React.useState([]); const menuRef = React.useRef(null); const onToggleClick = () => { setIsOpen(!isOpen); }; const menuItems = [ Item 1 Item 2 Item 3 Item 4 , , Item 5 Item 6 Item 7 Item 8 ]; const createFavorites = (favIds: string[]) => { const favorites: JSX.Element[] = []; menuItems.forEach((item) => { if (item.type === DropdownList) { item.props.children.filter((child) => { if (favIds.includes(child.props.value)) { favorites.push(child); } }); } else if (item.type === DropdownGroup) { item.props.children.props.children.filter((child) => { if (favIds.includes(child.props.value)) { favorites.push(child); } }); } else { if (favIds.includes(item.props.value)) { favorites.push(item); } } }); return favorites; }; React.useEffect(() => { if (favorites.length === 0) { const firstElement = menuRef?.current?.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, [favorites]); const onFavorite = (event: any, value: string, actionId: string) => { event.stopPropagation(); if (actionId === 'fav') { const isFavorite = favorites.includes(value); if (isFavorite) { setFavorites(favorites.filter((fav) => fav !== value)); } else { setFavorites([...favorites, value]); } } }; return ( // eslint-disable-next-line no-console setIsOpen(isOpen)} toggle={(toggleRef) => ( {isOpen ? 'Expanded' : 'Collapsed'} )} ref={menuRef} onActionClick={onFavorite} // eslint-disable-next-line no-console onSelect={(_ev, value) => console.log('selected', value)} > {favorites.length > 0 && ( {createFavorites(favorites)} )} {menuItems} ); };