I want to come up with a nested if ternary operator with react components but am being challenged , this is my logic :
if (value==='bank' && is_valid_iban && is_completed) {
return <Checked/>
}
else if (is_completed) {
return <Checked/>
}
else if (value==='businessplan' && is_required) {
return <NotChecked/>
}
This was my change :
{
(!value=== 'bank' || is_valid_iban) &&
is_completed ? (<Checked/>) : (value ==='businessplan' && is_required && (<NotChecked/>))
}
What could be the best way of coming up with a ternary operator for the logic above.
Thanks
Make it Simple:
{(value === "bank" && is_valid_iban && is_completed) || is_completed ? (
<Checked />
) : (value === "businessplan" && is_required) ? (
<NotChecked />
) : (
<NotChecked />
)}
This solution seeks to simplify the below given set of conditions:
if (value==='bank' && is_valid_iban && is_completed) {
return <Checked/>
} else if (is_completed) {
return <Checked/>
} else if (value==='businessplan' && is_required) {
return <NotChecked/>
}
It is observed from the above that is_completed
is part of the first & second conditions. Something like this: ((A && B && C) || C)
which can be represented as (A && B) || C
.
Using a standard if..else
structure:
if ((value === 'bank' && is_valid_iban) || is_completed) return <Checked />
else if (value === 'businessplan' && is_required) return <NotChecked />
else return null;
Using ternary ?:
return (
((value === 'bank' && is_valid_iban) || is_completed)
? <Checked />
: (value === 'businessplan' && is_required)
? <NotChecked />
: null
);
When using ?:
please always indent the code so it is readable. Same applies for if else
as well; however, the if else
structure is a lot more readable than ?:
.