Home > Back-end >  on change of defaultOpenKeys values does not rer-ender antd menu component
on change of defaultOpenKeys values does not rer-ender antd menu component

Time:12-09

What I want:

I want to open (expand) the submenu of a specific menu when I change/update the defaultOpenKeys value.

What I've tried:

const [submenu, setSubmenu] = useState([]);
useEffect(() => {
  setSubmenu(["sub1"]);
}, []);

...

<Menu style={{ width: 256 }} defaultSelectedKeys={["4"]} defaultOpenKeys={submenu} mode="inline">
  <Menu.Item key="1">Option 1</Menu.Item>
  <Menu.Item key="2">Option 2</Menu.Item>
  <SubMenu key="sub1" title="Submenu">
    <Menu.Item key="3">Option 3</Menu.Item>
    <Menu.Item key="4">Option 4</Menu.Item>
  </SubMenu>
</Menu>;

In here, The submenu is an empty array at first, but whenever the page loads, useEffect does update the value of submenu and set to the ["sub1"]. What I believe is, whenever the state values do change, the page should re-render, so <Menu defaultOpenKeys={['sub1']} ...> should update like this, right?

But in here, if I pass <Menu defaultOpenKeys=['sub1'] ... > at first then this works as I expected, but If I pass the defaultOpenKeys value from the state, then this does not work as I expected (if the initial value of state is ['sub1'] then it also works fine).

Here is the code sandbox, where I've included both working and not working demo.

enter image description here

UPDATED:

After @HDM91 answer,

I've tried with another prop provided by antd, which is openKeys and it does open the submenu at first, but was unable to close it, or even it does block other submenus from opening/closing.

<Menu
 style={{ width: 256 }}
 defaultSelectedKeys={["4"]}
 openKeys={submenu} // blocks other submenu by closing and opening
 mode="inline"
>

CodePudding user response:

I've just tried with openKeys and and handle onOpenChange to set new openkeys into submenu state it's fine:

  const [submenu, setSubmenu] = useState([]);
  useEffect(() => {
    setSubmenu(["sub1"]);
  }, []);
  return (
    <Menu
      style={{ width: 256 }}
      defaultSelectedKeys={["4"]}
      defaultOpenKeys={submenu}
      openKeys={submenu}
      onOpenChange={(openKeys) => {
       setSubmenu(openKeys);
      }}
      mode="inline"
    >
      <Menu.Item key="1">Option 1</Menu.Item>
      <Menu.Item key="2">Option 2</Menu.Item>
      <SubMenu key="sub1" title="Submenu">
        <Menu.Item key="3">Option 3</Menu.Item>
        <Menu.Item key="4">Option 4</Menu.Item>
      </SubMenu>
    </Menu>
  );
  • Related