I would like to clarify a doubt on React Conditional Rendering with Switch Case
I have an implementation with conditions. ie I have to set a string value based on boolean case
For example
let str = "";
switch(some object)
{
case object.yes: // The case here is boolean. IS it possible to set boolean case. I did try but the value is not set correctly based on the case in the str variable.
str = "Yes"
break:
case object.no:
str = "No"
break;
}
IF the above code is not possible, I will use if ... else. But during code review, surely I will be asked why I did not use Switch instead of if ...else. I want to give a convincing answer. I did seach tutorials but I can only find string case and not boolean case for React.
Just want to verify if boolean case is possible.
CodePudding user response:
let str = "";
switch (true) {
case object.yes
str = "Yes"
break;
case object.no:
str = "No"
break;
default:
str = ""
}
CodePudding user response:
The cleanest solution is to use an IIFE
const object = {
yes: true,
no: false
}
const str = (() => {
switch (true) {
case object.yes: // The case here is boolean. IS it possible to set boolean case. I did try but the value is not set correctly based on the case in the str variable.
return "Yes";
case object.no:
return "No";
default:
return "Unknown";
}
})();
console.log(str);