Cheng Cheng - 3 months ago 170
React JSX Question

React-bootstrap how to capture the value of dropdown list

I figured out how to use react-bootstrap to display a dropdown list:

<DropdownButton bsStyle="success" title="Choose" onSelect={this.handleSelect} >
<MenuItem key="1">Action</MenuItem>
<MenuItem key="2">Another action</MenuItem>
<MenuItem key="3">Something else here</MenuItem>
</DropdownButton>


But how am I suppose to write the handler for onSelect to capture the option being selected? I tried this but don't know what to write inside:

handleSelect: function () {
// what am I suppose to write in there to get the value?
},


Also, is there a way to set an option to be selected by default?

Thank you!

Answer

The onSelect function is passed the selected value

<DropdownButton title='Dropdowna' onSelect={function(evt){console.log(evt)}}>
  <MenuItem eventKey='abc'>Dropdown link</MenuItem>
  <MenuItem eventKey={['a', 'b']}>Dropdown link</MenuItem>
</DropdownButton>

In this case if you select the first option, 'abc' is printed, in the second option you can see an object can be passed in as well.

So in your code

handleSelect: function (evt) {
    // what am I suppose to write in there to get the value?
    console.log(evt)
},

I'm not sure what you mean by a default value since this isn't a select - the button text is whatever is in the title attribute. If you want to handle a default value you could just set a value when value is null.