Introduction to React Conditional Rendering

If you are interested to learn about the React Events

In React, you can conditionally render components. There are several ways to do this.

In React, conditional rendering works the same way as the conditions work in JavaScript. We use JavaScript operators to create elements representing the current state, and then React Component update the UI to match them.

From the given scenario, we can understand how conditional rendering works. Consider an example of handling a login/logout button. The login and logout buttons will be separate components. If a user logged in, render the logout component to display the logout button. If a user not logged in, render the login component to display the login button. In React, this situation is called as conditional rendering.

There is more than one way to do conditional rendering in React. They are given below.

  • if
  • ternary operator
  • logical && operator
  • switch case operator
  • Conditional Rendering with enums

if Statement

We can use the if JavaScript operator to decide which component to render.

Example:

We’ll use these two components:

function MissedGoal() {
  return <h1>MISSED!</h1>;
}

function MadeGoal() {
  return <h1>Goal!</h1>;
}

Example:

Now, we’ll create another component that chooses which component to render based on a condition:

function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

Try changing the isGoal attribute to true:

Example:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={true} />);

Logical && Operator

Another way to conditionally render a React component is by using the && operator.

Example:

We can embed JavaScript expressions in JSX by using curly braces:

function Garage(props) {
  const cars = props.cars;
  return (
    <>
      <h1>Garage</h1>
      {cars.length > 0 &&
        <h2>
          You have {cars.length} cars in your garage.
        </h2>
      }
    </>
  );
}

const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

If cars.length is equates to true, the expression after && will render. Try emptying the cars array:

Example:

const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

Ternary Operator

Another way to conditionally render elements is by using a ternary operator.

condition ? true : false

We will go back to the goal example.

Example:

Return the MadeGoal component if isGoal is true, otherwise return the MissedGoal component:

function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

Switch case operator

Sometimes it is possible to have multiple conditional renderings. In the switch case, conditional rendering is applied based on a different state.

Example

function NotificationMsg({ text}) {  
  switch(text) {  
    case 'Hi All':  
      return <Message: text={text} />;  
    case 'Hello JavaTpoint':  
      return <Message text={text} />;  
    default:  
      return null;  
  }  
}  

Conditional Rendering with enums

An enum is a great way to have a multiple conditional rendering. It is more readable as compared to switch case operator. It is perfect for mapping between different state. It is also perfect for mapping in more than one condition. It can be understood in the below example.

Example

function NotificationMsg({ text, state }) {  
  return (  
    <div>  
      {{  
        info: <Message text={text} />,  
        warning: <Message text={text} />,  
      }[state]}  
    </div>  
  );  
}  

Conditional Rendering Example

In the below example, we have created a stateful component called App which maintains the login control. Here, we create three components representing Logout, Login, and Message component. The stateful component App will render either or depending on its current state.

import React, { Component } from 'react';    
// Message Component   
function Message(props)   
{   
    if (props.isLoggedIn)   
        return <h1>Welcome Back!!!</h1>;   
    else  
        return <h1>Please Login First!!!</h1>;   
}   
// Login Component   
function Login(props)   
{   
   return(   
           <button onClick = {props.clickInfo}> Login </button>   
       );   
}    
// Logout Component   
function Logout(props)   
{   
    return(   
           <button onClick = {props.clickInfo}> Logout </button>   
       );   
}   
class App extends Component{    
   constructor(props)   
    {   
        super(props);    
        this.handleLogin = this.handleLogin.bind(this);  
          this.handleLogout = this.handleLogout.bind(this);   
      this.state = {isLoggedIn : false};   
    }   
   handleLogin()   
    {   
        this.setState({isLoggedIn : true});   
    }   
    handleLogout()   
    {   
        this.setState({isLoggedIn : false});   
    }   
    render(){   
        return(   
            <div>   
        <h1> Conditional Rendering Example </h1>  
                <Message isLoggedIn = {this.state.isLoggedIn}/>               
                {   
                    (this.state.isLoggedIn)?(   
                    <Logout clickInfo = {this.handleLogout} />   
                    ) : (   
                    <Login clickInfo = {this.handleLogin} />   
                    )   
                }   
            </div>         
            );   
    }   
}   
export default App;    

Output:

When you execute the above code, you will get the following screen.

React Conditional Rendering

After clicking the logout button, you will get the below screen.

React Conditional Rendering

Preventing Component form Rendering

Sometimes it might happen that a component hides itself even though another component rendered it. To do this (prevent a component from rendering), we will have to return null instead of its render output. It can be understood in the below example:

Example

In this example, the is rendered based on the value of the prop called display Message. If the prop value is false, then the component does not render.

import React from 'react';   
import ReactDOM from 'react-dom';   
function Show(props)   
{   
    if(!props.displayMessage)   
        return null;   
    else  
        return <h3>Component is rendered</h3>;   
}   
ReactDOM.render(   
    <div>   
        <h1>Message</h1>  
        <Show displayMessage = {true} />    
    </div>,    
    document.getElementById('app')   
);  

Output:

React Conditional Rendering
Introduction to React Conditional Rendering
Show Buttons
Hide Buttons