React: If Else conditions in JSX

In this article, we will see how to add If and If/Else conditions in JSX in React.

JSX If condition using && operator

If we are just planning to display something conditionally we can use a if condition in JSX.

In Javascript, true && expression will evaluate to expression and false && expression evaluates to false.
Hence, we can have a if condition in JSX using the && operator as shown below.

class Hello extends Component {
    constructor(props) {
        super(props);
        this.state = {
            messages : 10
        }
      }

  render() {
    return (
      <div className="helloContainer">
            { this.state.messages > 0 &&
                <div>You have {this.state.messages} messages!</div>
            }
      </div>
    );
  }
}

Output:
You have 10 messages!
 

JSX If/Else condition using ?: operator

We can add an if/else in JSX using the ?: operator.

class Hello extends Component {
    constructor(props) {
        super(props);
        this.state = {
            messages : 0
        }
      }

  render() {
    return (
      <div className="helloContainer">
            { this.state.messages > 0 ? (
                <div>You have {this.state.messages} messages!</div>
                ) : (
                <div>You have no messages!</div>
            )}
      </div>
    );
  }
}

Output:
You have no messages!
 

© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags