skip to Main Content

please help me.
I have a problem with the ant-design Menu component, where the menu doesn’t read the state changes that occur.

Here I simulate, when the button is clicked it will change the defaultSelectedKeys based on the select state value, but defaultSelectedKeys doesn’t change.

import React from 'react';
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group',
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}

const items: MenuProps['items'] = [
  getItem('Navigation One', 'sub1', <MailOutlined />, [
    getItem('Item 1', 'g1', null, [getItem('Option 1', '1'), getItem('Option 2', '2')], 'group'),
    getItem('Item 2', 'g2', null, [getItem('Option 3', '3'), getItem('Option 4', '4')], 'group'),
  ]),

  getItem('Navigation Two', 'sub2', <AppstoreOutlined />, [
    getItem('Option 5', '5'),
    getItem('Option 6', '6'),
    getItem('Submenu', 'sub3', null, [getItem('Option 7', '7'), getItem('Option 8', '8')]),
  ]),

  { type: 'divider' },

  getItem('Navigation Three', 'sub4', <SettingOutlined />, [
    getItem('Option 9', '9'),
    getItem('Option 10', '10'),
    getItem('Option 11', '11'),
    getItem('Option 12', '12'),
  ]),

  getItem('Group', 'grp', null, [getItem('Option 13', '13'), getItem('Option 14', '14')], 'group'),
];

const App: React.FC = () => {
  const [select, setSelect] = React.useState(['3'])
  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
  };

  return (
  <React.Fragment>
    <Menu
      onClick={onClick}
      style={{ width: 256 }}
      defaultSelectedKeys={select}
      defaultOpenKeys={['sub1']}
      mode="inline"
      items={items}
    />
{/*
update state here
*/}
    <button onClick={() =>{setSelect(['2'])}}>click</button>
    </React.Fragment>
  );
};

export default App;

Here the image

expect:
when the button is clicked. then the active menu is option 2

2

Answers


  1. State Update and Re-rendering:
    Verify State Change: Ensure that the defaultSelectedKeys state is actually being updated when the button is clicked. Use console logs or debugging tools to confirm.
    Force Re-render: If the state change is detected but the Menu isn’t updating, try forcing a re-render using techniques like:
    Adding a key prop to the Menu component that changes when the state updates.
    Using React.memo or useMemo to optimize re-renders for specific components.
    . defaultSelectedKeys vs. selectedKeys:
    Correct Prop: Use defaultSelectedKeys to set initial selected items, but use selectedKeys to control selected items dynamically based on state changes.
    State Management: Manage the selectedKeys state effectively using hooks like useState.
    . Component Structure and Nesting:
    Menu Placement: Make sure the Menu component is placed within a parent component that re-renders when the state changes.
    Nested Menus: If using nested Menus, ensure correct key usage and state management for each level.
    . Additional Considerations:
    Menu Mode: Be mindful of the Menu’s mode (inline, vertical, etc.) and its implications for selected item behavior.
    Ant Design Version: Check for known issues or limitations related to your specific Ant Design version.

    Login or Signup to reply.
  2. You should use selectedKeys instead of defaultSelectedKeys.

    <Menu
          onClick={onClick}
          style={{ width: 256 }}
          selectedKeys={select}
          mode="inline"
          items={items}
        />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search