manually give path to the new route highlighting the menu item react code example

Example: manually give path to the new route highlighting the menu item react

// passing in the routes as a list of items in the header

//all paths that are not in menu item also needed to be added to the items list or on the path will give an error for undefined key

//create a state for an active path
const [active, setActive] = useState('');

// routes file may have seprate object paths
const items = [
  { key: 'product', path: '/admin/dashboard' },
  { key: 'create-product', path: '/admin/create-product' },
  { key: 'create-product-manage', path: '/admin/create-product-manager' },
  { key: 'product-manager', path: '/admin/product-manager/:id' },
  { key: 'product-managers', path: '/admin/product-managers' },
  { key: 'sale', path: '/admin/sales' },
  { key: 'analyze', path: '/admin/analyze' },
];

// for each menu item click
const onClickMenu = item => {
    const clicked = items.find(_item => _item.key === item.key);
    history.push(clicked.path);
  };

// paths must be under useEffect so that under every rerender the path must be setActive
useEffect(() => {
    let path = window.location.pathname.split('/').pop();

    if (path === '') {
      path = 'dashboard';
    }

    setActive(path);

    setSelectedKey(
      items.find(_item => window.location.pathname.startsWith(_item.path).key)
    );
  }, [window.location.pathname]);

// in the return function each menu item needs to have the path
<Menu>
   <Menu.Item
              className="item"
              key="product"
              icon={<Product isActive={active === 'dashboard'} />}
              onClick={() => history.push('/admin/dashboard')}
            />

            <Menu.Item
              className="item"
              key="sale"
              icon={<Sale isActive={active === 'sale'} />}
              onClick={() => history.push('/admin/sale')}
            />
  </Menu>

Tags:

Misc Example