I’m mapping an array[key,val] to dynamically create dropdowns. I want to pass the key from the select onChange handler so I can store the selected value in the correct index in the array. How do I pass the key.
JavaScript
x
10
10
1
AdditionQueryArray.map((val, key) => {
2
<Select
3
onChange={this.AdditionalFieldHandleChange(key)}
4
isMulti
5
options={this.state.fieldOptions}
6
/>
7
}
8
9
AdditionalFieldHandleChange = (selectedOption,key) => {// saving selected option in array by key here}
10
Advertisement
Answer
You could do something like this:
JavaScript
1
13
13
1
AdditionQueryArray.map((val, key) => {
2
<Select
3
onChange={this.AdditionalFieldHandleChange(key, event)}
4
isMulti
5
options={this.state.fieldOptions}
6
/>
7
}
8
9
AdditionalFieldHandleChange = (key, event) => {
10
const val = event.target.value //this will be the selected value
11
// saving selected option in array by key here
12
}
13
This way can be used for all types of form fields, be it input or selections.