Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React bootstrap default selected value for dropdown

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?

like image 748
iRohitBhatia Avatar asked May 22 '26 12:05

iRohitBhatia


1 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>
like image 109
yoni Avatar answered May 24 '26 01:05

yoni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!