Nick Bolsh
Nick Bolsh

Reputation: 150

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?

Upvotes: 4

Views: 2977

Answers (3)

Bin HOU
Bin HOU

Reputation: 71

Firstly you cannot use multiple components in one statement. You must do like this:

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

Ok, for big DOM, just like this:

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

or

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

BTW, I have created a small library to do a lisp style if - else

import { _if } from 'jsxcond';

...

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

Upvotes: 0

Dmitry Shvedov
Dmitry Shvedov

Reputation: 3286

Another way of doing if-else can be done by use of an IIFE as suggested here: https://facebook.github.io/react/tips/if-else-in-JSX.html.

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

Upvotes: 1

awei
awei

Reputation: 1164

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

Upvotes: 6

Related Questions