The if-else Statement is One of the Conditional Rendering in React

ReactJS if else Statement

When we are building React applications, we may often need to show or hide some HTML based on a certain condition. Luckily, JSX conditional rendering in React works the same way conditions work in JavaScript. We have four different approaches there are if/else, element variables, ternary conditional operator, and short circuit operator. In this article, we will learn about the if else statement in Reactjs.


class Greeting extends Component {

        this.state = {
            isLoggedIn : false

            return <h1>Welcome John</h1>
            return  <h1>Welcome Guest</h1>


reactjs if else statement


  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 the message to be conditionally rendered based on the ‘isLoggedIn’ state.
  4. If I am logged in, the message “welcome john” should be displayed else the message “welcome guest” is displayed. To do that, we should use the if-else statement.
  5. In the render method of the class component, we need to add if-else condition. We set the condition like “if(this.state.isLoggedIn” and if the condition is true we returned the message “welcome john”. And the else condition, that is if not logged in we returned the message “welcome guest”
  6. See the above output, the message “welcome guest” is displayed successfully because “isLoggedIn” is set false. If you set to ‘true’ then the message “welcome John” is displayed.


Leave a Reply