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
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
Share Improve this question asked Jan 16, 2021 at 23:23 ThomasThomas 431 silver badge6 bronze badges2 Answers
Reset to default 5The 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).
The React docs have a section for lists & keys that will help you solve this. I have included an example for you:
const myArray = ["Moo Moo", "Burt", "Little Kitty", "Juan"]
const options = myArray.map((item) => {
return (
<option key={item} value={item}>
{item}
</option>
)
})
return (
<Container>
<Row>
<Col>
<Form>
<Form.Group controlId="exampleForm.SelectCustom">
<Form.Label>Custom select</Form.Label>
<Form.Control as="select" custom>
{options}
</Form.Control>
</Form.Group>
</Form>
</Col>
</Row>
</Container>
)
If it's an array
type, then mapping {item.value}
will not work, since there are not key/value pairs in an array, just values.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745167731a4614735.html
评论列表(0条)