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

Solutions on MaxInterview for manually give path to the new route highlighting the menu item react by the best coders in the world

showing results for - "manually give path to the new route highlighting the menu item react"
Elisa
18 Aug 2016
1// passing in the routes as a list of items in the header
2
3//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
4
5//create a state for an active path
6const [active, setActive] = useState('');
7
8// routes file may have seprate object paths
9const items = [
10  { key: 'product', path: '/admin/dashboard' },
11  { key: 'create-product', path: '/admin/create-product' },
12  { key: 'create-product-manage', path: '/admin/create-product-manager' },
13  { key: 'product-manager', path: '/admin/product-manager/:id' },
14  { key: 'product-managers', path: '/admin/product-managers' },
15  { key: 'sale', path: '/admin/sales' },
16  { key: 'analyze', path: '/admin/analyze' },
17];
18
19// for each menu item click
20const onClickMenu = item => {
21    const clicked = items.find(_item => _item.key === item.key);
22    history.push(clicked.path);
23  };
24
25// paths must be under useEffect so that under every rerender the path must be setActive
26useEffect(() => {
27    let path = window.location.pathname.split('/').pop();
28
29    if (path === '') {
30      path = 'dashboard';
31    }
32
33    setActive(path);
34
35    setSelectedKey(
36      items.find(_item => window.location.pathname.startsWith(_item.path).key)
37    );
38  }, [window.location.pathname]);
39
40// in the return function each menu item needs to have the path
41<Menu>
42   <Menu.Item
43              className="item"
44              key="product"
45              icon={<Product isActive={active === 'dashboard'} />}
46              onClick={() => history.push('/admin/dashboard')}
47            />
48
49            <Menu.Item
50              className="item"
51              key="sale"
52              icon={<Sale isActive={active === 'sale'} />}
53              onClick={() => history.push('/admin/sale')}
54            />
55  </Menu>