Reputation: 3173
I try simplify the code in one method, how to avoid duplicate code in this case. Without having two method, how to implement and loop in one.
const residentsConfigurations = configurations.filter(({alarmType}) => alarmType === alarmTypes.Care || alarmType === alarmTypes.Wandering)
const staffConfigurations = configurations.filter(({alarmType}) => alarmType === alarmTypes.Assistance || alarmType === alarmTypes.Panic)
{currentTab === 0 &&
residentsConfigurations.map((configuration, index) =>
<Grid key={index} item xs={12} lg={6}>
<Item
key={configuration.alarmType}
configuration={configuration}
changeBehavior={this.changeBehavior}
changeConfiguration={this.changeConfiguration}
/>
</Grid>
)}
{currentTab === 1 &&
staffConfigurations.map((configuration, index) =>
<Grid key={index} item xs={12} lg={6}>
<Item
key={configuration.alarmType}
configuration={configuration}
changeBehavior={this.changeBehavior}
changeConfiguration={this.changeConfiguration}
/>
</Grid>
)}
Upvotes: 0
Views: 72
Reputation: 3173
I find out more flexible variant, we can add more tabs or configurations if we want.
const tabsConfigurations = {
'0': [alarmTypes.Care, alarmTypes.Wandering],
'1': [alarmTypes.Assistance, alarmTypes.Panic],
}
let types = tabsConfigurations[currentTab]
{configurations.filter(({alarmType}) => types.includes(alarmType)).map((configuration, index) =>
<Grid key={index} item xs={12} lg={6}>
<Item
key={configuration.alarmType}
configuration={configuration}
changeBehavior={this.changeBehavior}
changeConfiguration={this.changeConfiguration}
/>
</Grid>
)}
Upvotes: 0
Reputation: 2311
getConfigGrid(configurations) {
return (
configurations.map((configuration, index) => (
<Grid key={index} item xs={12} lg={6}>
<Item
key={configuration.alarmType}
configuration={configuration}
changeBehavior={this.changeBehavior}
changeConfiguration={this.changeConfiguration}
/>
</Grid>
)
);
}
const residentsConfigurations = configurations.filter(({alarmType}) => alarmType === alarmTypes.Care || alarmType === alarmTypes.Wandering)
const staffConfigurations = configurations.filter(({alarmType}) => alarmType === alarmTypes.Assistance || alarmType === alarmTypes.Panic)
{currentTab === 0 && this.getConfigGrid(residentsConfigurations)}
{currentTab === 1 && this.getConfigGrid(staffConfigurations)}
Upvotes: 1
Reputation: 173
Refactored:
const newConfig = configurations.filter(({ alarmType }) =>
currentTab === 1
? alarmType === alarmTypes.Assistance || alarmType === alarmTypes.Panic
: alarmType === alarmTypes.Care || alarmType === alarmTypes.Wandering;
);
{
newConfig.map((configuration, index) => (
<Grid key={index} item xs={12} lg={6}>
<Item
key={configuration.alarmType}
configuration={configuration}
changeBehavior={this.changeBehavior}
changeConfiguration={this.changeConfiguration}
/>
</Grid>
));
}
Upvotes: 2