Search code examples
javascriptreactjsantd

How can i make common componet for antd Menu?


i want to make antd menu common component from that i will import antd menu in my Menu.js component and whenver i want to use antd menu i will import my menu.js component instead of antd menu but in this structure i got one error

here is my menu.js

import React from 'react';
import { Menu as AntMenu } from 'antd';



const Menu = ({items, ...extraAttributes }) => {
  return (
    <AntMenu
      items={items}
      {...extraAttributes}
    />
  );
}
export default Menu;

but now how can i use menu.Item , menu.SubMenu , and Menu.ItemGroup because i didnt exported or returned in my component how can i write menu.js that makes my componet same as like ant i mean menu.Item , menu.SubMenu , and Menu.ItemGroup can be used by importing from my Menu.js component

i tried exporting

import { Menu as AntMenu } from 'antd';
const { SubMenu, Item, ItemGroup } = AntMenu;

export { Menu, SubMenu, ItemGroup, Item };

still it not working for me


Solution

  • Assign them to your Menu

    const Menu = ({items, ...extraAttributes }) => {
      return (
        <AntMenu
          items={items}
          {...extraAttributes}
        />
      );
    }
    
    const { SubMenu, Item, ItemGroup } = AntMenu;
    
    Menu.SubMenu = SubMenu
    Menu.ItemGroup = ItemGroup
    Menu.Item = Item
    
    export default Menu
    

    Now you can

    import Menu from "path/to/my/menu"
    
    function Comp() {
      return (
        <Menu>
          <Menu.Item>Item</Menu.Item>
        </Menu>
      )
    }