I have a React Component where I have a Form with multiple Selects.
The options of these Select components is passed to the SearchComponent as props.
I want to store the selected options in local state, and once the Submit of the form is pressed it is sent to the parent component that passes a function as a prop - searchStatements.
Since the select is multiple, I have an array of all the options that can be selected and stored in state.
class SearchComponent extends Component {
state = {
companies: [],
years: [],
currencies: []
};
render() {
return (
<Form
onSubmit={(e) => {
this.props.searchStatements(this.state.years,
this.state.currencies,this.state.companies);
}}
>
<Select
multiple=true
value={this.state.companies}
options={this.props.companies}
onChange={(e) => this.handleSelectChange('companies', e)}
/>
<Select
multiple=true
value={this.state.years}
options={this.props.years}
onChange={(e) => this.handleSelectChange('years', e)}
/>
<Select
multiple=true
value={this.state.currencies}
options={this.props.currencies}
onChange={(e) => this.handleSelectChange('currencies', e)}
/>
</Form>
);
}
handleSelectChange = (name, v) => {
if (name === 'currencies') {
const newArray = this.state.currencies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'companies') {
const newArray = this.state.companies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'years') {
const newArray = this.state.years;
newArray.push(v);
this.setState({'years': newArray});
}
};
}
The initial state is like this -
state = {
companies: [],
years: [],
currencies: []
};
When a currency USD is added, it should become
state = {
companies: [],
years: [],
currencies: ['USD']
};
Again, when a currency GBP is added, it should become
state = {
companies: [],
years: [],
currencies: ['USD', 'GBP']
};
However, in the handleSelectChange(), after adding a couple of options, it becomes something like this -
state = {
companies: [['GOOGLE'], ['GOOGLE', 'FACEBOOK']],
years: [],
currencies: [['USD'], ['USD', 'GBP']]
};
How do I change handleSelectChange() such that my final output looks something like this -
state = {
companies: ['GOOGLE', 'FACEBOOK'],
years: [],
currencies: ['USD', 'GBP']
};
vin thehandleSelectChangemethod?["USD", "GBP"].