5 Ways To Implement Conditional Rendering In React Applications

July 06, 2023
5 Ways to Implement Conditional Rendering in React 1



Conditional rendering in React is anything but simple. You have to write lines and lines of boilerplate code to render a simple UI markup. Luckily, there is more than one way to render in React.

In this article, we will explore five ways to implement conditional rendering in React to help you understand how to render components in React. However, before we proceed, let’s recap conditional rendering.

Conditional rendering tells elements in React when and when not to render. The code barges onwards if the condition is valid and comes to a halt if not.

react dev jobs

5 Ways to Implement Conditional Rendering in React

Knowing different ways to render elements in React helps find the perfect fit for unique scenarios. Each has its pros and cons. So, without further ado, let’s begin and explore which one is best for when.

1) If-Else Condition

The if-else in React works the same way it does in JavaScript. The condition goes in the if section with expected results in True and False blocks. Below is a simple example of if-else in action. The code will show upload success if the condition is true, or else throw upload failure.

const Payments = ({status}) =>{

   return  (

       <div>

           <h2>Payment Status</h2>

           {

               if(status === "SUCCESS"){

                   <UploadSuccess></UploadSuccess>

               }else{

                   <UploadFailure></UploadFailure>

               }

           }

       </div>

   )

2) Ternary Operator

The ternary operator provides an even simpler alternative to implementing conditional rendering in React. This method saves you from writing bulky codes after the curly brackets and works with three operands.

const Uploads = ({status}) =>{

   return  (

       <div>

           <h2>Upload Status</h2>

           {

               status ? <UploadSuccess></UploadSuccess> : <UploadFailure></UploadFailure>

           }

       </div>

   )

}

3) Short-Circuit or && Operator

It is the go-to method to implement conditional rendering in React if you work with integers and the output relies upon some calculations. However, before we proceed, let’s explore its intricate mechanics.

With the example below, you can understand how short-circuiting works in React. Suppose you write a code to print a specific message only if the input answer is above 10. Here is how the && operator can help you achieve the desired.

const showMessage = (answersSubmitted) => {

   answersSubmitted > 10 && alert("You have scored Grade A+ in your Test");

}

In the code above, the message appears if the answer is above 10, or else it doesn’t.

That said, let’s turn to React conditional rendering. The code below illustrates how to use the && operator or short-circuiting to render components.

const Voucher = ({BonusPoints}) =>{

   return (

       <div>

           ---

           ---

           {

               BonusPoints>10 && <GiftVoucherModalComponent>

                                   </GiftVoucherModalComponent>

           }

       </div>

   )

}

4) Switch Case Operators

The next method to implement conditional rendering in React is via switch case operators. They come in handy when you work with multiple use cases and components and desire to produce unique outputs.

There is no friendlier way to render than switch case operators at such times, as they allow you to categorize and define your outcome in front of each case like below.

const Students = ({class}) => {

   return (

       {

           switch(class){

               case 9 : <NinthStandardLandingPage></NinthStandardLandingPage>;

                break;

               case 10 : <TenthStandardLandingPage></TenthStandardLandingPage>;

                break;

               case 11 :

<EleventhStandardLandingPage></EleventhStandardLandingPage>;

                break;

               default : <TwelthStandardLandingPage></TwelthStandardLandingPage>

           }

       }

   )

}

Moreover, you can also make the above code more readable by placing switch cases in different functions.

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) Higher-Order Components (HOC)

Higher-order Components or HOC give React components more privilege than any other way and treat them as First Class Functions, which implies they can pass as an argument and also return. When following generic architecture, using HOC is the best way forward.

However, Higher-Order Components also work like a charm when implementing conditional rendering in React.

function enhanceComponent(GenericComponent){

   return function enhancingComponent({...props}){

       return <GenericComponent {...props}></GenericComponent>

   }




const EnhancedComponent = enhanceComponent(GenericComponent)

<EnhancedComponent props={props.value}></EnhancedComponent>

Now let’s transform the above code for React conditional rendering to see the full functionality of the method.

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>

Conclusion

Implementing conditional rendering in React may seem tricky initially, but once you know different ways to render components in React, you can make the same simple. React deploys many use cases for application development, and the more adept you are with React conditional rendering methods, the better it is.

Also Read: How To Set Up Server Side Rendering (SSR) With React

react jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US