Search code examples
reactjsantd

Why react Dropdown component need pass the data to a const variable or it could not be rendered


I am new to react. Rencently I met a condition that the drop down component could not directly render the data that we passed into.

My component code:

function PackageSelection({data, switchPackage}) {
  const items = data
  return (
    <Space direction="vertical" size={16}>
      <Dropdown
        menu={{
          items,
        }}
        trigger={['click']}
        arrow={{pointAtCenter: true}}
      >
      </Dropdown>
    </Space>
  )

}

I found if we do not have this code "const items = data", component would be rendered failed. For now, I could not figured out why?

The data passed-into is:

[
    {
        "key": "official",
        "type": "group",
        "label": "official item",
        "children": [
            {
                "key": "01.00.00.01_official",
                "label": "01.00.00.01"
            },
            {
                "key": "01.00.00.02_official",
                "label": "01.00.00.02"
            },
          ]
     }
]


Solution

  • There really is no difference between:

    function PackageSelection({data, switchPackage}) {
      const items = data
      return (
        <Space direction="vertical" size={16}>
          <Dropdown
            menu={{
              items,
            }}
            trigger={['click']}
            arrow={{pointAtCenter: true}}
          >
          </Dropdown>
        </Space>
      )
    }
    

    and:

    function PackageSelection({data, switchPackage}) {
      return (
        <Space direction="vertical" size={16}>
          <Dropdown
            menu={{
              data,
            }}
            trigger={['click']}
            arrow={{pointAtCenter: true}}
          >
          </Dropdown>
        </Space>
      )
    
    }
    

    The only explanation I can think of is that the property of the object passed to menu should be called items


    In javaScript

    {
    foo,
    }
    

    is the same as :

    {
    foo: foo
    }
    

    so if you try:

    function PackageSelection({data, switchPackage}) {
      return (
        <Space direction="vertical" size={16}>
          <Dropdown
            menu={{
              items: data,
            }}
            trigger={['click']}
            arrow={{pointAtCenter: true}}
          >
          </Dropdown>
        </Space>
      )
    }
    

    it should work.