How do I create a dynamic drop down list with react-bootstrap How do I create a dynamic drop down list with react-bootstrap reactjs reactjs

How do I create a dynamic drop down list with react-bootstrap


You can start with these two functions. The first will create your select options dynamically based on the props passed to the page. If they are mapped to the state then the select will recreate itself.

 createSelectItems() {     let items = [];              for (let i = 0; i <= this.props.maxValue; i++) {                       items.push(<option key={i} value={i}>{i}</option>);             //here I will be creating my options dynamically based on          //what props are currently passed to the parent component     }     return items; }  onDropdownSelected(e) {    console.log("THE VAL", e.target.value);    //here you will see the current selected value of the select input}

Then you will have this block of code inside render. You will pass a function reference to the onChange prop and everytime onChange is called the selected object will bind with that function automatically. And instead of manually writing your options you will just call the createSelectItems() function which will build and return your options based on some constraints (which can change).

  <Input type="select" onChange={this.onDropdownSelected} label="Multiple Select" multiple>       {this.createSelectItems()}  </Input>


My working example

this.countryData = [    { value: 'USA', name: 'USA' },    { value: 'CANADA', name: 'CANADA' }            ];<select name="country" value={this.state.data.country}>    {this.countryData.map((e, key) => {        return <option key={key} value={e.value}>{e.name}</option>;    })}</select>


bind dynamic drop using arrow function.

class BindDropDown extends React.Component {  constructor(props) {    super(props);    this.state = {      values: [        { name: 'One', id: 1 },        { name: 'Two', id: 2 },        { name: 'Three', id: 3 },        { name: 'four', id: 4 }      ]    };  }  render() {    let optionTemplate = this.state.values.map(v => (      <option value={v.id}>{v.name}</option>    ));    return (      <label>        Pick your favorite Number:        <select value={this.state.value} onChange={this.handleChange}>          {optionTemplate}        </select>      </label>    );  }}ReactDOM.render(  <BindDropDown />,  document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root">    <!-- This element's contents will be replaced with your component. --></div>