React bootstrap default selected value for dropdown

Viewed 3149

I was using react-bootstrap library and I wanted to have default selected value.

I went through their docs and I wasn't able to find anything related to pass/set default value.

This is how I am currently using

const dropDownQuestion = (props) => {
  const { options, upsideEmit, value } = props
  return (
    <DropdownButton
      id="dropdown-basic-button"
      onSelect={(eventKey) => upsideEmit(eventKey)}
    >
      {options.map((element) => (
        <Dropdown.Item key={element.id}>{element.value}</Dropdown.Item>
      ))}
    </DropdownButton>
  )
}

Where value happens to be optional default Value. Can someone help me how to achieve this with react-bootstrap dropdown?

2 Answers

It depends on what do you mean by default value. If you mean value that appears on the dropdown button before the user touch it, you can simply insert it (hard-coded or by variable) as the text of the Dropdown.Toggle, for example:

<Dropdown.Toggle id="dropdown-basic">
    Your "default value" here 
</Dropdown.Toggle>

If by default value you mean the value of the dropdown's selected item before the user touch it, it's up to you, by choosing it in the data structure you use to set the values, for example:

var options = ["1", "2", "3", "4", "5"];
let chosenValue=options[0] // The "default Value"
function onSelect(eventKey, event) { // user can change the "default value"
chosenValue=eventKey;
.
.
.
}


<Dropdown onSelect={onSelect}>
    <Dropdown.Toggle id="dropdown-basic" />
    <Dropdown.Menu>
      {options.map(option => (
        <Dropdown.Item
          eventKey={option}
          key={option}>
          {option}
        </Dropdown.Item>
      ))}
   </Dropdown.Menu>
</Dropdown>

You can use the active prop on the Dropdown.Item to highlight it, if that's what you mean?

A DropdownButton isn't designed as an input, so you can't have a "default value", each item in the menu is rendered as a button.

Related