Search code examples
reactjstypescriptantd

Adding element to antd Dropdown overlay property results in React single child error


Stripped down code:

const menu = (
  <Menu>
    <Menu.Item>
      1st menu item
    </Menu.Item>
  </Menu>
);

export const QBDropdown: React.FC = () => 
  <div>
    <Dropdown overlay={menu} />
  </div>

When attempting to populate the overlay property in the antd dropdown, the following error always occurs:

Error: React.Children.only expected to receive a single React element child.

It does so seemingly regardless of what I populate it with. A single <div></div> or <></> produces the same error. What's going on here?


Solution

  • The Dropdown menu must have a child. which can be verified using React.Children.only

     <div>
        <Dropdown overlay={menu}>
          <button>Something to trigger the menu</button>
        </Dropdown>
      </div>
    

    https://reactjs.org/docs/react-api.html#reactchildrenonly

    https://github.com/ant-design/ant-design/blob/bf72f5538a9a788639bd4b56a1ccc9f86ea453c3/components/dropdown/dropdown.tsx#L144