DEV Community

Cover image for Conditionally render your DOM in ReactJS
Vignesh Pugazhendhi
Vignesh Pugazhendhi

Posted on

Conditionally render your DOM in ReactJS

Most single page applications are dynamic and change content frequently depending upon the end user's actions.One of the features of reactjs that allows this is called conditional rendering. Reactjs allows us to render a fragment of DOM conditionally. This is very much similar to conditional statements in any programming language.

Conditions can be applied to a number of scenarios. The below are not limited to but are some cases where condtional rendering can be used:

  1. render data of an API call
  2. show or hide elements based on user's actions such as a button click or a change in the value of a dropdown
  3. to toggle application functionality
  4. hide or display elements based on roles (authorization)

Below are some of the ways to condtionally render a DOM fragment:

1. Using If...Else

This can be opted if and only if the condition holds two values.Following code snippet explains the use of If..Else conditional statement.

const DISCOUNTS=["offer',"promocode"];
export default function App({...props})=>{
   const [discountSelected,setDiscountSelected]=useState(DISCOUNTS[0]);
   function renderForm(){
      if(discountSelected===DISCOUNTS[0]){
         <form>
           <label>Offer Name</label>
           <input type="text" />
         </form>
      }else{
         <form>
           <label>Promocode Name</label>
           <input type="text" />
         </form>
      }
   }
   function handleDiscountChange(){
     if(discountSelected===DISCOUNTS[0]){
        setDiscountSelected(DISCOUNTS[1]);
     }else{
        setDiscountSelected(DISCOUNTS[0])
     }
   }
   return (
     <div>
        <button onClick={handleDiscountChange}>Change Discount Type</button>
        {renderForm()}
     </div>
   );
}

Enter fullscreen mode Exit fullscreen mode

We could have conditionally rendered the component inside the return statement but it is always advisable to keep your code clean.

2. Using Switch Statement

The above result could be achieved using a simple switch statement but always use a switch statement only when you want to render DOM based on many different values.

const AuthButton = props => {
  let { isLoggedIn } = props;

  switch (isLoggedIn) {
    case true:
      return <button>Logout</button>;
      break;
    case false:
      return <button>Login</button>;
      break;
    default:
      return null;
  }
};

Enter fullscreen mode Exit fullscreen mode

3. Using variables

Variables can be used to render DOM conditionally. Initialize a variable and set it value to some snippet of DOM based on the conditions.Below code fragment explains the use case

export default function App(){
    let { isLoggedIn } = this.state;
    let AuthButton;

    if (isLoggedIn) {
      AuthButton = <button>Logout</button>;
    } else {
      AuthButton = <button>Login</button>;
    }

    return (
      <div className="App">
        <h1>
           Conditional rendering using variables
        </h1>
        {AuthButton}
      </div>
    );

}

Enter fullscreen mode Exit fullscreen mode

4. Using ternary operator

Ternary operator is similar to If...Else statement expect for the fact that the code is clean and as small as possible.

export default function App({...props}){
  let { isLoggedIn } = this.state;

    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {isLoggedIn ? <button>Logout</button> : <button>Login</button>}
      </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

5. Using Short Circuit Evaluation
This can be used with a single condition or a combination of conditions. Below code fragment demonstrates the use case:

export const App=(props)=>{
  let { isLoggedIn } = this.state;

    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {isLoggedIn && <button>Logout</button>}
      </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

6. IIFEs

Immediately invoked functions or IIFEs can be used to execute a function code block with any of the above use cases:

export default function App(props){
  return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {(function() {
          if (isLoggedIn) {
            return <button>Logout</button>;
          } else {
            return <button>Login</button>;
          }
        })()}
      </div>
    );
}

``




Enter fullscreen mode Exit fullscreen mode

Top comments (0)