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.
Example:
class Greeting extends Component {
constructor(props){
super(props)
this.state = {
isLoggedIn : false
}
}
render(){
if(this.state.isLoggedIn){
return <h1>Welcome John</h1>
}
else{
return <h1>Welcome Guest</h1>
}
}
}
Output:
Steps:
- In the above code, we have simply created a class component called Greeting().
- Then we created a constructor and inside ‘this.state’ we create a state called isLoggedIn and initialize it to false.
- Now, what I want is 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 should use the if-else statement.
- 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”
- 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.