Henry Henry - 3 months ago 17
React JSX Question

How can I write an else if structure using React (JSX) - the ternary is not expressive enough

I want to write the equivalent in react:

if (this.props.conditionA) {
<span>Condition A</span>
} else if (this.props.conditionB) {
<span>Condition B</span>
} else {
<span>Neither</span>
}


So maybe

render() {
return (<div>
{(function(){
if (this.props.conditionA) {
return <span>Condition A</span>
} else if (this.props.conditionB) {
return <span>Condition B</span>
} else {
return <span>Neither</span>
}
}).call(this)}
</div>)
}


But that seems overly complex. Is there a better way?

Answer

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>;
}
Comments