Home > Net >  How to get extra properties from selected item using React DropdownButton
How to get extra properties from selected item using React DropdownButton

Time:04-01

I'm a Java developer working on a react prototype and stuck trying to retrieve the id property from the selected dropdown item, which we then should post to our api. The value shown for the user on the dropdown option is an actor's name whereas the api needs their id. I think I may be getting the syntax for this wrong somewhere but I can't see where. I've tried adding extra params to the handleSelect call, created another new handleClick function and added it to Dropdown. Item instead of DropdownButton, changed params and calls around, but I only get undefined for these fields and am running out of ideas now. Any help is much appreciated.

<DropdownButton 
onSelect={handleSelect} 
title={selected?.key || list[0].key}>
{list.map((item, index) => {
    return (
        <Dropdown.Item key={index} eventKey=. 
            {item.key} onSelect={handleClick}>
            {item.key}
            </Dropdown.Item>
           );
        })}
 </DropdownButton>
const handleSelect = (key, event, value) => {
  setSelected({
    key: key,
    value: event.target.value
  })

  setActorId(getSelectedActorId(value))
}

const handleClick = (eventKey, event) => {
  console.log(eventKey)
  console.log(event)
}

Thank you very much.

CodePudding user response:

Dropdown.Item just has a onClick property, but not an onSelect property: https://react-bootstrap.netlify.app/components/dropdowns/#dropdown-item-props. When you just need the actor's id for submitting, then I would only safe the id in the state and nothing else.

I have created a sandbox with some dummy data: https://codesandbox.io/s/vibrant-blackwell-h7s7op

  • Create a state for actor id
  • Set this state onSelect of the DropdownButton
  • Set appropriate eventKey to Dropdown.Item when iterating, so you get them out of onSelect callback

Edit: Dropdown is a button with an overlay menu. You usually don't display the selected valu in the button. For this case i would recommend you to use Form.Select component. I have adjusted the sandbox accordinly.

Edit2: I have also added a hacky dropdown button which changes its title according to the selected value. But I wouldn't recommend you doing it this way.

  • Related