3 Ways to Implement Conditional Rendering in React

Read it in 9 Mins

Last updated on
07th Jun, 2022
Published
21st Dec, 2021
Views
9,412
3 Ways to Implement Conditional Rendering in React

React allows users to build Single Page Applications (SPA), which are highly interactive and dynamic in nature. We can create components and render them, use states to store information, and many other features in React to build different types of applications. To have a comprehensive understanding of usereducer in React, click here.

When we develop applications there may be some situations where we need to restrict the access to the user in the application. At that stage some authentication mechanisms come into picture and progress the action by validation like the Login form Validation, signing into different applications etc. But how can one include these mechanisms in a React application? This can be done using an exceptional feature of React called as “Conditional Rendering”. 

What is conditional rendering in web applications?

It is a concept of rendering the components in a React application based on certain condition either true or false. With the help of conditional rendering, we can hide or show certain elements in an application and a lot more things to implement this concept during development of an application. In react, the feature of conditional rendering works on the same mechanism as the way conditions work in the JavaScript. 

We can apply the feature of conditional rendering in the following scenarios 

  • Hide or Show elements 
  • Authorization and Authentication Mechanism 
  • Render external data from an API 
  • Toggle the functionality of an application 

Let us consider a small example for user level actions. We will create a small application displaying the Login & Logout scenarios. These scenarios work on an alternative basis, like when login is called some text information like “welcome user” is displayed on the application & logout is displayed on the screen. And when logout is called some text like “Successfully logged out” & login button is displayed on the screen. This process of designing the pages in the application can be implemented based on the feature of conditional rendering in the React.

Commands to create React App

Open command prompt and write the following commands

npx create-react-app demo-app 
cd demo-app 
npm start 

We can see below how user-level actions are implemented using the conditional rendering feature in react: - 

Index.js (using if / else model) 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
// function describes the person who have logged into the application 
function LoggedInUser(props) { 
  return <div> 
     <h1 >Welcome, to Upgrad KnowledgeHut </h1 > 
     <p> You have loggined in successfully </p> 
   </div>; 
} 
// function describes the person who have logged out of the application 
function LoggedOutUser(props) { 
  return <div> 
     <h1 >Login to UKH </h1 > 
     <p>You have logged out, please log in again</p> 
   </div>; 
}  
// conditional rendering is implemented here, basic on the call 
// in the reactdom.render component 
// props value is given as input 
function LoggedStatus(props) { 
  const isLoggedIn = props.isLoggedIn; 
  // if “true”, redirect to loggedInUser function 
  if (isLoggedIn) { 
    return <LoggedInUser />; 
  } 
// if “false”, redirect to loggedOutUser function 
return <LoggedOutUser />; 
} 
// props value is initialized here 
ReactDOM.render( 
// rendering is performed based on the value of true or false 
// prop value can be set in using blue color area either true or false 
  <LoggedStatus isLoggedIn={false} />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
} 
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
} 

We can run the applications by plugging the codes in the corresponding files and then, in the terminal type “npm start” and the output is displayed on the browser. Every time you update any code in the react app files, and then save it, then the output is reflected on the browser directly. 

Output

  • If the prop value is “FALSE 

3 Ways to Implement Conditional Rendering in React

  • If the prop value is “TRUE  

3 Ways to Implement Conditional Rendering in React

While dealing with the above program, without changing the values in the render function either “true” or “false” manually, we can add functionality to the application by adding buttons. We can use the variables to store the elements, these variables help in rendering the part of the component based on certain conditions and keeping the rest undisturbed.  

The conditional rendering mechanism can be implemented variables and components. Below we are adding the components like Login & Logout to implement the functionality. And we also create a stateful component for rendering the activities through a class mechanism in react.  

We provide functionality using components and the code is as follows:  

Index.js (using if / else model) 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
// function describes the person who have logged into the application 
function LoggedInUser(props) { 
  return <div> 
     <h1>Welcome, to Upgrad KnowledgeHut </h1 > 
     <p> You have loggined in successfully </p> 
   </div>; 
} 
// function describes the person who have logged out of the application 
function LoggedOutUser(props) { 
  return <div> 
     <h1 >Login to UKH </h1 > 
     <p>You have logged out, please log in again</p> 
   </div>; 
} 
// component -- Login 
function LoginButton(props) { 
  return ( 
    <button onClick={props.onClick}> 
      Log In 
    </button> 
  ); 
} 
// component -- Logout 
function LogoutButton(props) { 
  return ( 
    <button onClick={props.onClick}> 
      Log Out 
    </button> 
  ); 
}
// Implementing a Stateful Component, for rendering the components 
class LoginControl extends React.Component { 
  constructor(props) { 
    super(props); 
    this.handleLoginClick = this.handleLoginClick.bind(this); 
    this.handleLogoutClick = this.handleLogoutClick.bind(this); 
    this.state = {isLoggedIn: false}; 
  } 
// when one component is clicked, the other component would be in off state 
  handleLoginClick() { 
    this.setState({isLoggedIn: true}); 
  } 
  handleLogoutClick() { 
    this.setState({isLoggedIn: false}); 
  } 
// Rendering the components based on the clicking event 
  render() { 
    const isLoggedIn = this.state.isLoggedIn; 
    let button; 
    if (isLoggedIn) { 
      button = <LogoutButton onClick={this.handleLogoutClick} />; 
    } else { 
      button = <LoginButton onClick={this.handleLoginClick} />; 
    } 
    return ( 
      <div> 
        <LoggedStatus isLoggedIn={isLoggedIn} /> 
        {button} 
      </div> 
    ); 
  } 
} 
ReactDOM.render( 
  <LoginControl/>, 
  document.getElementById('root') 
); 

Output 

  • If the rendering call is “FALSE  

3 Ways to Implement Conditional Rendering in React

  • If the rendering call is “TRUE 

3 Ways to Implement Conditional Rendering in React

Conditional Rendering in React

React facilitates the creation of multiple components, which in turn encloses the behaviour that we need for developing an application using it. After defining the component in the application, we render the components based on some conditions. Based on the conditions we apply the component decides which element to return at the end.  

We can follow some other techniques to do conditional rendering in React. They are: - 

  • If else 
  • ternary operator 
  • logical AND operator 

If else

In React, it is the simple conditional rendering statement implemented in render method. In a component, it is restricted to a particular block. This if-else statement is worked in a 2-way process. 2-way process is like if one block of code does not satisfy the given condition, it will go to other block of code.  If the given condition is true, it returns the block of code present in “if” else it returns the block of code present in “else”.    

Syntax

if(condition) 
{ 
 // block of code 
} 
Else 
{ 
 // block of code 
} 

An example of the “if” statement is developing an application is given below: - 

Index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
// defining the functions 
function Before(props) {   
  return <h3>Before the company name is KnowledgeHut,  
    and is not Considered now with the same name</h3>;   
}   
function After(props) {   
  return <h1 >Company name is changed,  
and it is Upgrad KnowledgeHut Now</h1>;   
}   
// props value is passed here 
// and the corresponding output is rendered 
// using the conditional rendering 
function Change(props) {   
  const isConsidered = props.isConsidered;   
  if (isConsidered) {   
    return <After />;   
  }   
  else { 
  return <Before />;   
  } 
}   
// props value is initialized here   
// prop value can be set in using blue color area either true or false 
ReactDOM.render(   
  <Change isConsidered={true} />,   
  document.getElementById('root')   
);   

We can run the applications by plugging the codes in the corresponding files and then, in the terminal type “npm start” and the output is displayed on the browser. Every time you update any code in the react app files, and then save it, then the output is reflected on the browser directly. 

Output

  • If the prop value is “FALSE

3 Ways to Implement Conditional Rendering in React

  • If the prop value is “TRUE 

3 Ways to Implement Conditional Rendering in React

Ternary operator

This operator is used in the situations, where we have two blocks of code alternate each other on a given condition. This operator is as like the “if-else” statement. This ternary operator is used as the short form notation for if-else, and it is written in a single line. It takes 3 operands and returns the output according to it.

Syntax 

condition ? true : false 

If the condition is true, the 1st statement will be rendered, else the 2nd one would render

An example for the ternary operator in conditional rendering is given as below:

Index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
// defining functions 
function CompanyName() { 
  return <h1 >Name is Upgrad KnowledgeHut</h1>; 
} 
function CompanyLocation() { 
  return <h1 >Location is Bangalore</h1>; 
} 
// taking prop value as input 
function Company(props) { 
  const info = props.info; 
  return ( 
    <> 
// usage of ternary operator 
      { info ? <CompanyName/> : <CompanyLocation/> } 
    </> 
  );
Profile

Harsha Vardhan Garlapati

Blog Writer at KnowledgeHut

Harsha Vardhan Garlapati is a Data Science Enthusiast and loves working with data to draw meaningful insights from it and further convert those results and implement them in business growth. He is a final year undergraduate student and passionate about Data Science. He is a smart worker, passionate learner,  an Ice-Breaker and loves to participate in Hackathons to work on real time projects. He is a Toastmaster Member at S.R.K.R Toastmasters Club, a Public Speaker, a good Innovator and problem solver.