Search code examples
reactjsnext.jsantdant-design-pro

how can we have different functions on ANt design menu items in the new version?


I'm sure if you're using ant design menu component you've got the same error:

Warning: [antd: Menu] children will be removed in next major version. Please use items instead.

the new way to make this is:

const items = [
  { label: 'item 1', key: 'item-1' },
  { label: 'item 2', key: 'item-2' },
  {
    label: 'sub menu',
    key: 'submenu',
    children: [{ label: 'item 3', key: 'submenu-item-1' }],
  },
];
return <Menu items={items} />

and you can define your function and use it like this:

return <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />;

how can i have different functions on my items?

i'll be glad if someone help me with this

in the old way i could easily define any functions i want on any items


Solution

  • Actually, we can add functions to the items array as well

    const [current, setCurrent] = useState();
    
    const func = () => {
       setCurrent(e.key);
    }
    
    const func2 = () => {
       setCurrent(e.key);
    }
    
    const items = [
      { 
        label: 'item 1', 
        key: 'item-1' 
        onClick: func,
        className: class1,
      },
      { 
        label: 'item 1', 
        key: 'item-1' 
        onClick: func2,
        className: class2,
      },,
      {
        label: 'sub menu',
        key: 'submenu',
        children: [{ label: 'item 3', key: 'submenu-item-1' }],
      },
    ];
    
    
    return <Menu selectedKeys={[current]} mode="horizontal" items={items} />;