How can I write an else if structure using React (JSX) - the ternary is not expressive enough
Why do you say that the ternary is not expressive enough?
render() {
return <span>
{this.props.conditionA ? "Condition A"
: this.props.conditionB ? "Condition B"
: "Neither"}
</span>;
}
If you don't need the <div>
, just return the <span>
elements:
render() {
if (this.props.conditionA) {
return <span>Condition A</span>;
} else if (this.props.conditionB) {
return <span>Condition B</span>;
} else {
return <span>Neither</span>;
}
}
You can even move the last return
statement out of the else
block.
In general, you don't have to embed everything inside JSX. It's perfectly fine to compute values beforehand, just like you do elsewhere:
render() {
let content;
if (this.props.conditionA) {
content = <span>Condition A</span>;
} else if (this.props.conditionB) {
content = <span>Condition B</span>;
} else {
content = <span>Neither</span>;
}
return <div>{content}</div>;
}
You have to do that whenever you need / want to use a statement.
Calculating the value, binding to a variable, then outputting later is better. If you do want complex logic inline, you could use &&
and ||
:
render() {
return (<div>
{
this.props.conditionA && <span>Condition A</span>
|| this.props.conditionB && <span>Condition B</span>
|| <span>Neither</span>
}
</div>)
}
Edit:
As others pointed out, you can also remove that wrapping div and still use this approach:
render() {
return (
this.props.conditionA && <span>Condition A</span>
|| this.props.conditionB && <span>Condition B</span>
|| <span>Neither</span>
);
}