Skip to content
Advertisement

How to pass a key value into the onchange handler for a select dropdown

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}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement