Reputation: 872
I have 3 select like this
const { selectedOption , selectedOption2, selectedOption3} = this.state;
const value = selectedOption && selectedOption.value;
const value2 = selectedOption2 && selectedOption2.value;
const value3 = selectedOption3 && selectedOption3.value;
<Select
name="form-field-name1"
value={value}
onChange={this.handleChange}
options={[
{ value: 'Ados et jeunes', label: 'One' },
{ value: 'Pêche à la truite', label: 'Two' },
]}
/>
<Select
name="form-field-name2"
value={value2}
onChange={this.handleChange}
options={[
{ value: 'XXXX', label: 'OneX' },
{ value: 'XXXXXX', label: 'TwoX' },
]}
/>
<Select
name="form-field-name3"
value={value3}
onChange={this.handleChange}
options={[
{ value: 'rrrrrr', label: 'Oner' },
{ value: 'rrrrrrrr', label: 'Twor' },
]}
/>
and when i don't know how to change the value with handlechange
handleChange(selectedOption) {
this.setState({ selectedOption });
console.log(`Selected: ${selectedOption.label}`);
}
how can i update selectoption 2 and 3 in the same function
Upvotes: 1
Views: 889
Reputation: 382
Unsure if this is the best way for doing this, but for the size of the form it should still be easy enough to follow.
handleChange = (event) =>{
switch(event.target.id){
case 'select1':
// Your code for specific select
break;
case 'select2':
// Your code for specific select
break;
case 'select3':
// Your code for specific select
break;
}
}
Then in each of the selects just add an id tag for 'select1', '...2','...3'
Upvotes: 0
Reputation: 281744
In your handleChange function, you need to send the id of the select field whose value changes like onChange={(selectedOption) => this.handleChange(selectedOption, 'selectedOption2')}
<Select
name="form-field-name1"
value={value}
onChange={(selectedOption) => this.handleChange(selectedOption, 'selectedOption')}
options={[
{ value: 'Ados et jeunes', label: 'One' },
{ value: 'Pêche à la truite', label: 'Two' },
]}
/>
<Select
name="form-field-name2"
value={value2}
onChange={(selectedOption) => this.handleChange(selectedOption, 'selectedOption2')}
options={[
{ value: 'XXXX', label: 'OneX' },
{ value: 'XXXXXX', label: 'TwoX' },
]}
/>
<Select
name="form-field-name3"
value={value3}
onChange={(selectedOption) => this.handleChange(selectedOption, 'selectedOption3')}
options={[
{ value: 'rrrrrr', label: 'Oner' },
{ value: 'rrrrrrrr', label: 'Twor' },
]}
/>
and then you can have the handleChange function like
handleChange(selectedOption, key) {
this.setState({ [key]: selectedOption });
}
You can also have a look at How to avoid binding in render method
to achieve the same result without using arrow function
Upvotes: 2