Home > Mobile >  React Antd dropdown throws if menu is dynamic
React Antd dropdown throws if menu is dynamic

Time:02-02

I am trying to get an Antd dropdown based on an array but it keeps failing with Error: React.Children.only expected to receive a single React element child.

I have seen the other threads about it but I am confused because my menu works if the data is static: Here's a snippet

  var items = [
    {
      key: '0',
      label:  'item0',
    },
    {
      key: '1',
      label:  'item1',
    }
  ];
  
  var items2 = []
  for (let item of items) items2.push({key: items2.length.toString(), label: item.label})
  
  console.log(items, items2, JSON.stringify(items), JSON.stringify(items2), JSON.stringify(items) === JSON.stringify(items2) )
  
  return (<>
    <Dropdown menu={{ items }} trigger={['click']}>
      <a onClick={(e) => e.preventDefault()}>
        {name} <DownOutlined />
      </a>
    </Dropdown>
    <Dropdown menu={{ items2 }} trigger={['click']}>
      <a onClick={(e) => e.preventDefault()}>
        {name} <DownOutlined />
      </a>
    </Dropdown>
  </>)
  

As expected, items and items2 are the same by construction, and JSON.stringify(items) === JSON.stringify(items2) ) is true

However, clicking on the first dropdown with items works, while clicking on the second one throws.

How can I solve that issue?

CodePudding user response:

the first works only by coincidence! because the variable name is items and since you have to specifie the property name which is also items it works so

{{items}}

is in fact :

{{items:items}}

for the second one you should mention the items property because you have a differently named variable

{{items:items2}}

CodePudding user response:

replace menu={{ items2 }} to menu={{ items: items2 }}
the menu attribute must have the items property
I hope it help

CodePudding user response:

You should write it like this

<Dropdown menu={{ items: items2 }} trigger={["click"]}>

enter image description here

enter image description here

  • Related