Hi I'm having 2 Dropdowns but for that I'm managing 2 states with it. Please help me to reduce the duplicated code. Suppose, if i want to have 10 dropdowns then my number of states and same methods gets repeated the same. If there a way to refractor the code to reduce the number of states and methods would be better.
Note : I have a class based component
this.state = {
isOpen: false,
selected: null,
isDisabled: false,
isOpen1: false,
selected1: null,
isDisabled1: false,
isOpen2: false,
selected2: null,
isDisabled2: false, }
Inside Constructor
this.options = [
<SelectOption key={0} value={hourTxt} isPlaceholder />,
<SelectOption key={1} value={weekTxt} />,
<SelectOption key={2} value={dayTxt} />,
<SelectOption key={3} value={neverTxt} />,
];
this.options1 = [
<SelectOption key={0} value={hourTxt} />,
<SelectOption key={1} value={weekTxt} />,
<SelectOption key={2} value={dayTxt} isPlaceholder />,
<SelectOption key={3} value={neverTxt} />,
];
this.onToggle = (isOpen) => {
this.setState({
isOpen
});
};
this.onToggle1 = isOpen1 => {
this.setState({
isOpen1
});
};
this.onSelect = (event, selection, isPlaceholder) => {
if (isPlaceholder){
this.clearSelection();
}
else {
this.setState({
selected: selection,
isOpen: false
},() => { this.postSelectData()
});
}
};
this.onSelect1 = (event, selection, isPlaceholder) => {
if (isPlaceholder) this.clearSelection1();
else {
this.setState({
selected1: selection,
isOpen1: false
},() => { this.postSelectData()
});
}
};
this.clearSelection = () => {
this.setState({
selected: null,
isOpen: false
},() => { this.postSelectData()
});
};
this.clearSelection1 = () => {
this.setState({
selected1: null,
isOpen1: false
},() => { this.postSelectData()
});
};
Under render()
const {isOpen, selected,isOpen1, selected1} = this.state
Under return()
<Select
variant={SelectVariant.single}
onToggle={this.onToggle}
onSelect={this.onSelect}
selections={selected}
isOpen={isOpen}
>
{this.options}
</Select>
<Select
variant={SelectVariant.single}
onToggle={this.onToggle1}
onSelect={this.onSelect1}
selections={selected1}
isOpen={isOpen1}
>
{this.options1}
</Select>