Search code examples
javascriptreactjsreact-bootstrap

React bootstrap: How to pass an array to options in Form.Control


I am using Form.Control to create a drop down list and I would like to make the list dynamic. My code looks like this:

render() {
 return (

 <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}>
  <option value={myArray[0].value}> myArray[0].value </option>
  <option value={myArray[1].value}> myArray[1].value </option>
 </Form.Control>

 )
}

Obviously this only works when myArray has two elements. I would like to find a way to pass myArray into the options of 'Form.Control' dynamically. I have found answers in here on how to do it with Select but it does not seem to work with Form.Control as ="select" as I have here.

Thank you


Solution

  • The standard way to render a dynamic list of elements is to map an array:

    render() {
     return (
     <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}>
      {myArray.map(opt => (
        <option value={opt.value}>{opt.value}</option>
      ))}
     </Form.Control>
     )
    }
    

    React will ask you to provide a unique key prop for the mapped elements. This should ideally be a random id string, but you can add the index of the mapped array myArray.map((opt, i) => ... as a fallback while developing (this is also the default value which it uses when you do not provide one).