Is an if-else statement better than a ternary operator in React?

Ternary Operator in React

The benefit of this ternary operator in React is that it can be used inside the JSX. It is also called the shorthand method of an if-else statement. In this method, we have used the question mark ? and colon : symbol.

Syntax:

condtion ? ifConditionisTrue : ifConditionisFalse

In the above syntax, in the place of “condition”, we need to give any condition. If the condition is true before the colon statement is executed similarly if the condition is false after the colon statement is executed. Let’s see the example of a ternary operator in React.

Example:

class Greeting extends Component {
    constructor(props){
        super(props)

        this.state = {
            isLoggedIn : false
        }
    }

    render(){
        return(
       this.state.isLoggedIn?
       <div>Welcome John</div>:
       <div>Welcome Guest</div>  
        )
    }
}

Output:

ternary operator in react

Steps:

  1. In the above code, we have simply created a class component called Greeting().
  2. Then we created a constructor and inside ‘this.state’ we create a state called isLoggedIn and initialize it to false.
  3. Now, what I want is for the message to be conditionally rendered based on the ‘isLoggedIn’ state. If I am logged in, the message “welcome john” should be displayed else the message “welcome guest” is displayed. To do that, we can use the ternary operator in React.
    Inside the render() method, we have set the condition like “this.state.isLoggedIn”. In the statement1, we returned the message “welcome john” and in the statement2, we returned the message “welcome guest”.
  4. If the condition is true, the message “welcome john” is returned otherwise the message “welcome guests’ is returned.
  5. See the above output, the message “welcome guest” is displayed successfully because “isLoggedIn” is set to false. If you set it to ‘true’ then the message “welcome John” is displayed.

Leave a Reply