React 16+ Conditional Rendering Tutorial with Examples

By Digamber Rawat Last updated on
In this React 16+ conditional rendering tutorial, we are going to understand how can we work with different conditional statements. Being a web developer, we have to manage the data in our application. Conditional statements are used to execute various actions based on various conditions.

It could be a part of user interaction, data received by making a request, or even sometimes we have to hide or show certain elements in our app. This process is known as conditional Rendering in React.

Conditional Rendering in React is no rocket science if you are familiar with JavaScript, then you can perform different actions based on the specific conditional statements. Let’s find out How does conditional Rendering work in React? In simpler words, we will learn how to use all the below mentioned conditional statements in JSX.

React Add If…Else Statement in Render Method

The best way to add the if-else statement inside the render method in JSX, is to use the if-else statement inside the return method. We are showing the colors name inside the return method in React. You can also show the message to the user when the colors name is not available.

import React, { Component } from 'react';

export default class JSXComponent extends Component {
    colors = ['Red', 'Pink', 'Green', 'Blue'];

    render() {
        if (!this.colors.length) {
            return <span>Sorry, color list is empty.</span>;
        } else {
            return (
                <div>
                    {this.colors.map(item => item + ' ')}
                </div>
            );
        }
    }
}

Using Ternary Operator in React

Let’s assume if you want to find out the drinking age, you can use ternary operator in React. Ternary operator makes conditional rendering in React extremely easy, and It is far better then if-else statement in JSX.

import React, { Component } from 'react';

export default class JSXComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            beverage: 21
        }
    }

    render() {
        return (
            <div className="row">
                {
                    (this.state.beverage === 21)
                        ? <p> Beer </p>
                        : <p> Coke </p>
                }
            </div>
        );
    }
}

React Logical And && Operator Example

JavaScript offers logical AND && operators which helps in validating the satement using two values:

// And && operator output
true  && true;  // true
true  && false; // false
false && true;  // false
false && false; // false

Inside the render method, we are checking if the user and isAdmin both are true, then it will return the result using && logical operator in React.

import React, { Component } from 'react';

export default class JSXComponent extends Component {

    render() {
        let user = true;
        let isAdmin = true;
        let result;

        if (user && isAdmin) {
            result = 'Conditrion is truthy';
        }
        return (
            <div className="row">
                {
                    result
                }
            </div>
        );
    }
}

React Logical OR || Operator Example

Let us understand how to use logical OR || operator in React to check the statement passed inside the render() method. The logical OR || operator returns true if either of the value is true in the conditional statement in JSX.

You can check out the output if or operator is used:

// OR || operator output
true  || true;  // true
true  || false; // true
false || true;  // true
false || false; // false
import React, { Component } from 'react';

export default class JSXComponent extends Component {

    render() {
        let user = false;
        let isAdmin = true;
        let result;

        if (user || isAdmin) {
            result = 'Conditrion is truthy';
        } else {
            result = 'Conditrion is false';
        }
        return (
            <div className="row">
                {
                    result
                }
            </div>
        );
    }
}

React Switch Case Operator Example

In this step, we are going to learn how to use switch case conditional statement in React JSX. Let’s understand what switch statement is; it allows us to perform various actions based on multiple choices.

As you can see, we are trying to find out the current day based on JavaScript’s new Date method. We declared the switch case along with days name, here based on the present-day switch case would return the current day among other days.

import React, { Component } from 'react';

export default class JSXComponent extends Component {

    render() {
        let today = new Date().getDay();

        return (
            <div>
                {(() => {
                    switch (today) {
                        case 0:
                            return today = "Sunday";
                        case 1:
                            return today = "Monday";
                        case 2:
                            return today = "Tuesday";
                        case 3:
                            return today = "Wednesday";
                        case 4:
                            return today = "Thursday";
                        case 5:
                            return today = "Friday";
                        case 6:
                            return today = "Saturday";
                        default:
                            console.log('default');
                    }
                })()}
            </div>
        );
    }
}

Conclusion

Finally, we have completed conditional rendering in React tutorial with real-world examples. I hope this tutorial will help you to understand how to use conditional statements properly in React JSX. If you loved this tutorial, please share it with others as well.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.