You are currently viewing React Conditional Rendering using If else Statement

React Conditional Rendering using If else Statement

React if statement in return

If you check a condition using a condition statement like if/else and return a value, it is called conditional rendering. In React conditional rendering is a crucial aspect of building dynamic UI. You can use conditional rendering to display different elements or content based on conditions. We can implement conditional rendering in many ways like Ternary operation, Switch case operator, Higher-Order Components, IF with Logical && operator, etc but one of the simple and popular methods is using if statements within the return statement.

When you use the ternary operator or logical && operator for Conditional rendering can sometimes lead to nested or complex code structure, especially when dealing with multiple conditions. So, if statements in the return statement offer a more concise and readable alternative.

If/else Conditional Rendering

With this example, you can easily understand if/else conditional rendering. In this example, we get the user’s current location using the function “geolocation.getCurrentPosition()” and find the “latitude” in it. Then store the latitude and error value in state objects. And we set the condition in render() method, if the user’s allow the location permission, we return the user’s latitude. If the user deny location permission, we return the error message. And if users do not make any decisions, we return the message “Waiting for your response…”.

import React from "react";

class locationFinder extends React.Component {
    constructor(props) {
        super(props)
        this.state = { latitude: null, error: null }

        window.navigator.geolocation.getCurrentPosition(
            (position) => { this.setState({ latitude: position.coords.latitude }) },
            (error) => { this.setState({ error: error.message }) }
        );

    }
    render() {
        if (this.state.error && !this.state.latitude) {
            return
                 <div>Error : {this.state.error} </div>
        } if (!this.state.error && this.state.latitude) {
            return 
              <div> <p>Your latitude is {this.state.latitude}</p> </div>
        }
        else {
            return
                <div style={{marginTop:'50px'}}>Waiting for your response...</div>
        }
    }
}

export default locationFinder

If we run this code, we will have a location permission box open like this.

READ ALSO  Introduction to Next.js | Why should we Learn it?

react if statement in return

Here, the else part of the message is displayed because we haven’t selected options.

If you select allow option in the location permission box, your latitude will display like:

react if statement in return

If you select deny option, the error message will display:

react if statement in return

Explanation if/else conditional rendering:

if (this.state.error && !this.state.latitude) {
  return
      <div>Error : {this.state.error} </div>
        } 
if (!this.state.error && this.state.latitude) {
  return 
      <div> <p>Your latitude is {this.state.latitude}</p> </div>
        }
else {
  return
      <div style={{marginTop:'50px'}}>Waiting for your response...</div>
        }
  1. In this part of the code, the first condition we check is if there is an error (this.state.error) and if the latitude value is not available (!this.state.latitude). If the first condition is true, it executes the error message from this.state.error. If the first condition is false, the code moves to the second condition
  2. In the second condition, we check if there is no error (!this.state.error) and if the latitude value is available (this.state.latitude). This condition is true, it returns the latitude value from this.state.latitude. If both the first and second conditions are false, the code executes the else block.
  3. In the else block, we returned the value text “Waiting for your response…”

 

Using an if statement in return in React provides a concise and readable approach to conditional rendering. Although there are many ways of conditional rendering, using this method you can create maintainable and efficient reactive components.

Leave a Reply