Education

Methods for Conditional Rendering in React.js

logo

DhiWise

September 16, 2022
image
Author
logo

DhiWise

{
September 16, 2022
}

React.js lets you create different components, and each of them encapsulates several lifecycle methods. The lifecycle methods maintain or control the behavior of that component. You can render components depending on the application state. 

If you are rendering certain components and elements with any condition, then the process is called Conditional Rendering.

This article covers the different methods used to implement Conditional Rendering in React.js.

Most useful methods for Conditional Rendering in React

1. Use if … else statement

Conditional rendering works in the similar way condition works in JavaScript. You can use JavaScript operators like if/else for updating UI on state changes. 

For example: 

UserLoggedIn component
function UserLoggedIn(props) {
  return 

Welcome back!

Log out
; }
UserLoggedOut component
function UserLoggedOut(props) {
  return 

Sign in, please!

Log out
; }

When the user login status changes we must have a component to handle it. The LoggedStatus component displays either of LoggedIn and LoggedOut components based on the boolean value shown below.

function LoggedStatus(props) {
  const isUserLoggedIn = props.isUserLoggedIn;
  if (isUserLoggedIn) {
    return ;
  }

else {

return ;
     }

}
ReactDOM.render(
  ,
  document.getElementById('root')
);

2. Using Switch statement

Similar to if statements we can use switch statements for conditional rendering. Get the switch statement out of render in the function and then call it by passing the params. 

renderSwitch(param) {
  switch(param) {
    case 'foo':
      return 'bar';  
      default:
      return 'foo';
  }
}

render() {
  return (
    
{this.renderSwitch(param)}
); }

Also, you can inline the “switch” in the render function. In the below example we can see the implementation of a switch-like expression using a plain old javascript object:

Example: 

render ( ) {
  return (
    
{ { 'foo': , 'bar': }[param] }
) }

3. React Element Variable

Element variables hold JSX elements and only render the variables within JSX. You can conditionally assign elements or components to these variables but only outside the JSX and render the variable within JSX.

It is used to avoid the repeating return statement in the render( ) method. Use a variable to store the JSX element and initialize it when the condition is true. 

For Example,

class ConditionalRendering extends React.Component{    
       constructor(props){    
             super(props);    
            this.state ={    
                 isLoggedIn : true    
            }    
        }    
    
      render(){    
            let message;     
           if(this.state.isLoggedIn){    
                message = 
Welcome User
; } else{ message =
You need to login
; } return message; }; } export default ConditionalRendering;

4. Using Ternary operators

If you don’t want to use the if … else block, you can use a ternary operator instead. The ternary operator takes three operands and the syntax is:

Syntax:

condition? expression_if_true : expression_if_false

The expression can contain JSX, which can be applied to the different parts of components.

class ConditionalRendering extends React.Component{    
       constructor(props){    
            super(props);    
            this.state ={    
                        isLoggedIn : true    
            }    
      }    
          
      render(){    
            return this.state.isLoggedIn? 
Welcome!
: ""; }; } export default ConditionalRendering;

5. Short circuit operator and operator &&

It is a special case and simplified version of the ternary operator with && operator. The && operator evaluates the left side expression to generate the result, unlike the & operator which evaluates the right side of the expression first. It is useful if you want to render either something or nothing. 

Example:

class ConditionalRendering extends React.Component{    
       constructor(props){    
              super(props);    
              this.state ={    
                     isLoggedIn : true    
              }    
       }    
           
       render(){    
              return this.state.isLoggedIn && 
Welcome!
; }; } export default ConditionalRendering;

6. Immediately-Invoked Functions Expression (IIFE)

IIFE provides you with a way to execute a function immediately as soon as they are created. They are very useful since they do not affect the global object and help you to easily isolate variable declarations. 

Here is the syntax that define IIFE

function TestFunc ( ) {

}

TestFunc ( );

We can use the function as soon as it is defined:

(function TestFunc(/*args*/){    
}(/*args*/));

It can be defined with arrow function as well:

((/*args */) => {    
})(/* args */)  

Implementation using arrow function:

{(() => {
  if (isLoggedIn) {
    return ;
  } else {
    return ;
  }
})()}

So, these are the 6 different methods for implementing conditional rendering in React. Moreover, there are certain rules you need to follow while rendering the components or elements.

Rules for conditional Rendering:

  1. Avoid changing the position of the components arbitrarily to prevent components from unmounting and remounting.
  2. Avoid unnecessary rendering of components and elements with the render( ) method.

How to hide the React.js component 

Now you know how to render React components with conditional rendering. But in a few cases, you might want to hide the React.js component even though it is rendered by another component. 

This can be achieved by returning null in the render output. 

Example: Following example shows how to hide and show the React.js component.

function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }

  return (
    
Warning!
); } class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true}; this.handleToggleClick = this.handleToggleClick.bind(this); } handleToggleClick() { this.setState(state => ({ showWarning: !state.showWarning })); } render() { return (
); } }

Here you can clearly see if the value of prop is false then the component will not be rendered. And returning null from the render( ) method will not affect the component’s lifecycle methods. 

Summing Up:

Well, now you know about Conditional Rendering in React.js with almost all the useful methods. Also, we have seen how to hide the component while rendering it using the render( ) method.

“Make your React app development effortless, faster, and better with DhiWise- A new edge platform that aims to improve developer’s productivity with automation.” 

Explore more about DhiWise React Web Builder for faster Web application development and how it simplifies developer’s life with its out-of-the-box functionalities. 

Start using DhiWise today, sign up now!

Reference: 

https://reactjs.org/docs/conditional-rendering.html