Conditional Rendering in React Example & Tutorial

    Apr 27, 2020       by Suraj Roy
conditional-renderting-in-reactjs-application.jpg

For a Front-end developer like React.js, Understanding of conditional rendering is very important. It's not very high-level stuff but it makes the data binding with template easy, short, and effective. Conditional rendering means to show and hide the template section on the base of response from an API. A person who has worked a lot with javascript can easily manage this because this is similar to the way it in javascript.

This concept is applied mainly for following scenarios:

  • Showing/hiding elements
  • Toggling application functionality
  • Rendering external data from an API
  • Implementing permission levels
  • For authentication purposes

 

In this article, We will see some common ways to perform conditional rendering in React.js application.

 

Let's Get Started

1. Using If Else Statement in React

This is one of the easy ways to handle the flow when we have two or three different conditions on base of which we have to render the template section. Let's try to understand with the below example where we will have an array with fruit names in it and render the template on the base of array length.

 

 
import React from 'react';
 
class FruitComponent extends React.Component {
  fruits = ['mango', 'Apple', 'Banana', 'Orange'];
 
  render() {
    if (!this.colors.length) {
      return <span > Fruit list is empty. </span>;
    } else {
      return (
        <div> {
          this.fruits.map(item => item + ' ')
        } </div>
      );
    }
  }
}
 
export default FruitComponent
 

 

2. Using Ternary Operator in React

The ternary operator makes the task very easy and shorter. Let's understand with below example where we will show a user is adult person or a child on the base of the age.

 

 
import React from 'react';
 
class UserComponent extends React.Component {
  age = 15;
 
  render() {
 
    return (
      <div>
        {(this.age<18)?<p>Person is child</p>:<p>Person is adult</p>}
      </div>
    );
  }
}
 
export default UserComponent
 

 

3. Switch Case in React

Here we will see how to switch cases can be used for conditional rendering in React.js. As we already know that this loop is preferred while having many cases to handle. 

Let's try to understand with the below example:

 

 
import React from 'react';
 
class WeekComponent extends React.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:
              return today = "Invalid value";
            }
          })()
        }
      </div>
    );
  }
}
export default WeekComponent
 

 

4. Logical OR in React

I believe you are already fimiliar with this operator. Let's try to understand condition rendering with this operator using the below example.

 

 
import React from 'react';
 
class ABCComponent extends React.Component {
 
  render() {
    let isUserActive = false;
    let isAdmin = true;
    let result;
 
    if (isUserActive || isAdmin) {
      result = 'You are authorised';
    } else {
      result = 'You are not authorised';
    }
    return (
      <div> { result } </div>
    );
  }
}
export default ABCComponent
 

 

5. Logical And in React

Let's try to understand this with the above example when both the condition is true

 
import React from 'react';
 
class ABCComponent extends React.Component {
 
  render() {
    let isUserActive = false;
    let isAdmin = true;
    let result;
 
    if (isUserActive && isAdmin) {
      result = 'You are authorised';
    } else {
      result = 'You are not authorised';
    }
    return (
      <div> { result } </div>
    );
  }
}
export default ABCComponent
 

 

 

Conclusion

 

In this article, We learn about conditional rendering in React.js application.

I hope this article helped you. You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!

 


WHAT'S NEW

Find other similar Articles here: