Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use If-Else in JSX

I understand how to use it in simple situations:

{(this.state.show) ? <span>Show</span> : null}

But how to use it for big DOM?

{ if (this.state.show) {
  <span className={this.state.className}>Hi</span>
  {this.state.text}
} else {
  {this.state.text}
}
}

Of course, it doesn't work. How to do it correctly?

like image 327
Nick Bolsh Avatar asked Mar 17 '23 03:03

Nick Bolsh


1 Answers

You can't do that. I see two potential problems from what you've provided. First, you can only return one DOM node. Second, (and this might be because it's not your full code), your braces are not syntactically correct. Without knowing your full source code, you can try something like:

render: function() {
    var header;

    if (this.state.show) {
        header = <span className={ this.state.className }>Hi</span>;
    }
    return <div>
               { header }
               { this.state.text }
           </div>
}
like image 71
awei Avatar answered Mar 19 '23 17:03

awei