-1

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.

 AdditionQueryArray.map((val, key) => {
    <Select
        onChange={this.AdditionalFieldHandleChange(key)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (selectedOption,key) => {// saving selected option in array by key here}

2 Answers2

0

I think this is the answer you need: React js onClick can't pass value to method

example:

AdditionQueryArray.map((val, key) => {
    <Select
        onChange={() => this.AdditionalFieldHandleChange(key)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (selectedOption,key) => {// saving selected option in array by key here}

Maybe add the "val" option to the arguments because you have two arguments in your function definition?

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
0

You could do something like this:

AdditionQueryArray.map((val, key) => {
    <Select
        onChange={this.AdditionalFieldHandleChange(key, event)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (key, event) => {
const val = event.target.value //this will be the selected value
// saving selected option in array by key here
}

This way can be used for all types of form fields, be it input or selections.

Ankit Gupta
  • 175
  • 6