Hi when I have a condition output in frontend is there a possibility to make a else if ()
statement as well?
current code looks like:
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
}
Thanks in advance
Hi when I have a condition output in frontend is there a possibility to make a else if ()
statement as well?
current code looks like:
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
}
Thanks in advance
Share Improve this question edited Oct 10, 2017 at 11:28 Icepickle 12.8k3 gold badges37 silver badges50 bronze badges asked Oct 10, 2017 at 11:23 FelixFelix 5,62614 gold badges80 silver badges173 bronze badges 1-
Yeah, but you have to use a ternary operator. Or, you write the inverse condition and do your if block. Ternary opeartor would rather be like
condition ? iftrue : iffalse
. A better way to go about this however would be to extract your condition to a variable, and simply render the variable though, not need to pollute the visual tree – Icepickle Commented Oct 10, 2017 at 11:26
3 Answers
Reset to default 7You can use the conditional operator to make if/else expressions:
{someCondition === true ? (
<TrueComponent/>
) : (
<FalseComponent/>
)}
If you want an if/elseif/else, you can bine multiple conditionals together:
{someCondition === true ? (
<IfComponent/>
) : someOtherCondition === true ? (
<ElseIfComponent/>
) : (
<ElseComponent/>
)}
These things can be difficult to read, so you should consider pulling this code up above your return statement, using normal if's and elses:
let ponent;
if (someCondition === true) {
ponent = <IfComponent/>
} else if (someOtherCondition === true) {
ponent = <ElseIfComponent/>
} else {
ponent = <ElseComponent/>
}
return (
<div>{ponent}</div>
);
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
|| condition && ifConditionMetExpression
}
But this is a bit hard to read, I suggest you use ternaries instead:
{this.props.contentComponentData.typeOf === 1
? <ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
: condition
? ifConditionMetExpression
: null
}
(first condition)
? // if first condition true this part run
: (second condition)
? // if second condition true this part run
: // else part