I want to consolidate these if statements to make this efficient as possible while still having it be able to perform case 1 alone, case 2 alone, case 1 and 2 together, and neither case 1 nor case 2. Is there a way to do this?
if(x >= 100 && y < 100){
return(
<View>
<Text>
this is case 1
</Text>
</View>
)}
if(x < 100 && y >= 100){
return(
<View>
<Text>
this is case 2
</Text>
</View>
)}
if(x < 100 && y < 100){
return(
<View>
<Text>
this is case 1
</Text>
</View>
<View>
<Text>
this is case 2
</Text>
</View>
)}
if(x >= && y >= 100){
return(
<View>
<Text>
this is case 4
</Text>
</View>
)}
CodePudding user response:
Put your return value in a variable that you can concatenate for each case.
retval = '';
if (y < 100) {
retval =
<View>
<Text>
this is case 1
</Text>
</View>
;
}
if (x < 100) {
retval =
<View>
<Text>
this is case 2
</Text>
</View>
;
}
if (retval == '') {
// neither case
return(
<View>
<Text>
this is case 4
</Text>
</View>
);
} else {
return retval;
}
CodePudding user response:
Try this:
const el1 = (
<View>
<Text>
this is case 1
</Text>
</View>
)
const el2 = (
<View>
<Text>
this is case 2
</Text>
</View>
)
...
const conditions = {
el1,
el2,
...
}
if (x >= 100 && y < 100)
return conditions.el1
else if (x < 100 && y >= 100)
return conditions.el2
else if (x < 100 && y < 100)
return conditions.el1 conditions.el2
else
return conditions.default || ''
CodePudding user response:
You could collect the wanted strings and return either the formatted collection or case four.
const take = [];
if (x < 100) take.push('this is case 2');
if (y < 100) take.push('this is case 1');
return take.length
? take.map(/* your formatting */)
: 'this is case 4';