A picture of a computer screen, a React logo, and a CopyCat logo.

6 Great Methods to Achieve React JS Conditional Rendering With Examples

January 25, 2022
Abhishek KG
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Conditional Rendering in React using Vanilla JS requires too much boilerplate to render the UI Markup. We use if-else, switch case, ternary operator, or any other React JS conditional rendering mechanism to achieve the task. It depends on your requirements followed by the states you maintain to bind the condition.

const parent = document.getElementById("_parent-id");
const conditional_element = document.getElementById("_target-id");
if("-any-condition-"){
   parent.innerHTML += conditional_element;
}

In the example above, we are conditional rendering the ‘conditional_element’. If the statement inside is true, we are appending the element to the target parent.

The Various Rendering Options

With React, your whole code is broken into Components. Each Component has its UI Markups and is driven by the services and methods your Component needs. You might have use cases where you either have to toggle the React conditional render of the Components’ HTML or sometimes the entire Component.

React offers many ways to achieve that. It lets you define your conditions within your props or a state of a Component. You are no longer bound to just toggle the rendering of a specific element, but rather the whole Component itself.

Occasionally, you might have run into some use cases where you need to toggle elements based on certain conditions. For example, we could have a use case where we want to show or hide a loading spinner to the user whenever something is processing. The processing could be any service call, API requests, user authentication, etc. Here, we need to show the Spinner to create a good UX for the user, where he or she could see that something is being processed behind the picture. Using React, you can easily bind a state variable ( could be a boolean type ) for toggling between true and false whenever a service call is being made. Using this state variable, you can show or hide the spinner inside the component.

const shoppingComponent = ({loading}) => {
   return (
       <div>
           <p>Payment is being processed</p>
       {
           loading && <SpinnerComponent></SpinnerComponent>
       }
       </div>
   )

Here in the example above, shoppingComponent is a React Component that is receiving ‘loading’ as a prop. You can render the SpinnerComponent conditionally using this prop. ( Remember, a Component in React should return at least one UI Element. )

The above example shows one of the ways of React conditional render. Conditional rendering refers to the process when elements are not rendered unless necessary. Checking the Developer Console, you see that when the condition turns to a falsy value, the entire Component is removed from the DOM structure. ( Few examples of Falsy values are: false, 0 null, undefined, ‘’, NaN and 0n )

If you are not familiar with conditional rendering in React, this blog is the right place to get your concepts clearer. I will guide you though different ways of conditional rendering using simple code snippets.

Different Ways of React JS Conditional Rendering

Although conditional rendering in React is simply based on True or False conditions, there are different ways of doing it. You can write your logic within a JSX or even in the Component’s methods, It works like a charm.

Let’s see each conditional rendering way one by one:

1. Using Simple If-Else Condition:

This works in the same way a usual Javascript If-else would work. You need to place your condition within the If Section and accordingly place the desired Components within the True and False block.

The example below has a use case where you need to either show the PaymentSuccessfulComponent or the PaymentFailureComponent. The condition is based on the props coming by.

const Payments = ({status}) =>{
   return  (
       <div>
           <h2>Payment Status</h2>
           {
               if(status === "SUCCESS"){
                   <PaymentSuccess></PaymentSuccess>
               }else{
                   <PaymentFailure></PaymentFailure>
               }
           }
       </div>
   )
}

2. Using Ternary Operator:

This is an alternative way if you need to avoid the long lines of code following the curly braces. This is the only JavaScript operator that takes three operands. This is similar to the pure JavaScript way where you are using the Ternary Operator to achieve the desired output. We will follow the same example as above.

const Payments = ({status}) =>{
   return  (
       <div>
           <h2>Payment Status</h2>
           {
               status ? <PaymentSuccess></PaymentSuccess> : <PaymentFailure></PaymentFailure>
           }
       </div>
   )
}

3. Short-Circuiting using ‘&&’ Operator:

When you need to perform some calculation and based on the output you want to render a UI Component. In that case, you can use the Short Circuit way using ‘&&’ Operator. Before diving deep into this way, let’s first understand how Short-Circuiting works.

Let’s assume you need to print a message for the user, but only if the number of answers he has submitted is more than 8. In that case, using the ‘&&’ operator is useful.

const showMessage = (answersSubmitted) => {
   answersSubmitted > 8 && alert("You have scored Grade A in your Test");
}

Here, in the example above, if the condition is false, the console does not alert the user. Else, the console prompts the user with a message.

Now let’s see how you can use the ‘&&’ operator for conditional rendering in React.
The example below shows a GiftVoucherModalComponent to the user, where the component will have a Modal with the Voucher details. If the number of vantage points he has received is 10, he will be able to see the Modal.

const Voucher = ({vantagePoints}) =>{
   return (
       <div>
           ---
           ---
           {
               vantagePoints>10 && <GiftVoucherModalComponent>
                                   </GiftVoucherModalComponent>
           }
       </div>
   )
}

4. Using Switch Case Operators:

When you have a use case where you have ‘n’ number of Components and you want to show any one of them based on conditions for each. In those cases, Switch Case is a friendly choice you will have. It offers you to categorize your choices and write the resulting outcome against each case.

The example below is showing any one component based on certain conditions for their own.

const Students = ({class}) => {
   return (
       {
           switch(class){
               case 9 : <NinthStandardLandingPage></NinthStandardLandingPage>;
               	break;
               case 10 : <TenthStandardLandingPage></TenthStandardLandingPage>;
               	break;
               case 11 : <EleventhStandardLandingPage>
                         </EleventhStandardLandingPage>;
               	break;
               default : <TwelthStandardLandingPage></TwelthStandardLandingPage>
           }
       }
   )
}

The important point to note here is that you need a default case here in this Component because you cannot return an undefined JSX from a React Component.*

To make the above code cleaner, you can place your Switch Case in a different function in the component.

const Students = ({class}) => {
 
   const switchCaseEvaluator = () =>{
       {
           switch(class){
               case 9 : <NinthStandardLandingPage></NinthStandardLandingPage>;
               	break;
               case 10 : <TenthStandardLandingPage></TenthStandardLandingPage>;
               	break;
               case 11 :  <EleventhStandardLandingPage>
                          </EleventhStandardLandingPage>;
               	break;
               default : <TwelthStandardLandingPage></TwelthStandardLandingPage>
           }
       }
   }
  
   return (
      {
          this.switchCaseEvaluator();
      }
   )
}

5. Using Higher-Order Components (HOC)

Higher-Order Components lets you treat React Components as First Class Functions, where you can pass them as an argument or can return them from the Component. It makes developers’ life easier for the use cases that follow the generic Architecture. But apart from that, you can also use the HOC to conditionally render the Components. First, let’s get some understanding of HOC, and then we will go through using them to render.

function enhanceComponent(GenericComponent){
   return function enhancingComponent({...props}){
       return <GenericComponent {...props}></GenericComponent>
   }
}
 
const EnhancedComponent = enhanceComponent(GenericComponent);
 
<EnhancedComponent props={props.value}></EnhancedComponent>

In the example above, GenericComponent is passed as an argument to enhanceComponent function. Its job is to return an enhancedComponent using the props shared by the wrapping function. This makes it easy to use GenericComponent as a single source of truth and use them as some other Components developed from its props.

Now, let’s use the above example and transform it for conditional rendering. The use case could be like where we could either enhance the passed Generic Component or return other UI Markups if the condition is not followed. The example below demonstrates the same.

function enhanceComponent(GenericComponent){
   return function enhancingComponent({shouldRender}){
       if(shouldRender){
           return <GenericComponent></GenericComponent>
       }else{
           return <div>Does not need the condition</div>
       }
   }
}
 
const EnhancedComponent = enhanceComponent(GenericComponent);
 
<EnhancedComponent shouldRender={shouldRender}></EnhancedComponent>

6. Using Enums for React JS Conditional Rendering:

JavaScript’s Object can be used with Enums to create a map of key-value pairs. We can map it to different values and can use them in accordance with the use cases we follow. Let’s see how we can use enums in React to implement conditional rendering.

Let’s create an enum of Components.

const ENUM_OF_COMPONENTS = {
   pricing : <Pricing/>,
   checkout : <Checkout/>
}

Now let’s define each Component.

const Pricing = () =>{
   return <div>PRICING DATA</div>
}
 
const Checkout = () =>{
   return <div>CHECKOUT DATA</div>
}

Now depending on your use case, create a generic method that will help you render the above two Components conditionally.

class Enum extends React.Component{
   render(){
       return(
           <div>
               <ENUM_OF_COMPONENTS state="pricing"></ENUM_OF_COMPONENTS>
           </div>
       )
   }
}

Here, the conditional rendering will depend on the state you pass to the ENUM_OF_COMPONENTS.

Conclusion:

In summary, React conditional rendering is an important aspect of React which follows many use cases for Application Development. We discussed different ways of achieving conditional rendering in React. In particular, it depends on the approach that best fits your use case. You could also use Enum way if you want to make more readable code or better for simplicity, could use the If-Else way. Element variables can also be used. Element variables help you conditionally render a part of a component while the output stays fixed. In effect, I hope I have simplified your understanding of Conditional Rendering in React. Similarly, simplify your design to development process use CopyCat to render Figma designs to code automatically and eliminate development delays.

P.S. Visit the CopyCat blog for more such React.js resources

Interesting Reads From Our Blog:

Related Articles

  • React.js

    Top 17 VSCode Plugins to Boost Productivity as a Developer

    As front-end developers or software developers, you must work smartly, efficiently, productively, and DRY. You are known for building problem-solving tools for users. In this article, I will outline some VSCOde plugins that will help you increase your productivity as…

    December 8, 2022
  • React.js

    Complete Guide to Using Bootstrap Dropdown in React

    Introduction When building a web application, having a good navigation system makes your content easily accessible to users. With a dropdown menu, you can group related menu items for easy access. With Bootstrap, you can easily create a dropdown menu…

    December 20, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code