Search code examples
reactjshideaclantd

How to hide or prevent an antd submenu to be rendered?


I have a Menu as bellow:

<Menu>
  <SubMenu>
   <Menu.Item>Help</Menu.Item>
   <Menu.Item>Antd</Menu.Item>
  </SubMenu>
</Menu>

Now the problem is that I need to hide SubMenu or Menu.Item for some situations? something like below :

<Menu>
  <Acl item="submenu">
    <SubMenu>
      <Acl item="help">
        <Menu.Item>Help</Menu.Item>
      </Acl>
      <Menu.Item>Antd</Menu.Item>
    </SubMenu>
  </Acl>
</Menu>

The Acl component will check for user access to the menu and decide to hide or show the text.

Is there any code examples for antd to reach this result or any suggestions?

Note: Already I have implemented Acl as bellow:

import React, { Component } from 'react';

class Acl extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const props = this.props;
    if( hasAccess(props.item) )
      return <div>{props.children}</div>;
    return null;
  }
}

export default Acl;

But after render I got this error: Cannot read property 'indexOf' of undefined


Solution

  • I think it could be done as bellow:

    render() {
      const { getAccessByPath } = this.props; //selector from redux store
      <Menu>
      { getAccessByPath('submenu') ?
        <SubMenu>
         { getAccessByPath('submenu.help') ? 
             <Menu.Item>Help</Menu.Item> : ''
         }
         <Menu.Item>Antd</Menu.Item>
        </SubMenu> : ''
      }
      </Menu>
    }

    This works now but is so nasty and is not readable if I have more submenus an menu items (currently about 20) but I think there should be a better solution.