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>

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source