First time trying this so please bare with me.
I want to return some elements based on one of three conditions. Currently the code works for two conditions:
<h1 id="largeh1">
{isEnvironmentBFE
? outputEnFr(
"BFE Environment English Text",
"BFE Environment French Text",
this.props.lang
)
: outputEnFr(
"Acme Environment English Text",
"Acme Environment French Text",
this.props.lang
)
// Want third condition here
}
</h1>
I'd like to add one more condition for if the environment is "isEnvironmentBFE_OR_BFERENTAL" - so when people hit this third environment, it gives them different English / French values. Would like to stick with a ternary operator if possible.
Any idea how I can add a third condition in here?
<h1 id="largeh1">
{
isEnvironmentBFE
? (
outputEnFr(
"BFE Environment English Text",
"BFE Environment French Text",
this.props.lang
)
) : NEW CONDITIONAL HERE
? (NEW RESULT)
: (
outputEnFr(
"Acme Environment English Text",
"Acme Environment French Text",
this.props.lang
)
)
}
</h1>
This is equivalent to
if(isEnvironmentBFE)
//yadda
else if (foo)
//yadda yadda
else
//yadda
The most readable way to go about this is by moving that logic out of your return statement and creating a function for it which handles that logic. You can do this within the same component, or extract that function to a different file if it should be reusable on another component:
const Component = () => {
const renderText = () => {
if (...) {
return ...
} else if (...) {
return ...
}
return ...
}
return (
<h1>
renderText();
<h1>
)
};
If you would like to stick with a ternary you can do:
return condition1 ? (condition2 ? result1 : result2) : result3
Depends on your personal preference, although I suggest using an if-statement or a switch-statement for anything that has more than 1 condition as it is easier to read and comprehend what is happening.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With