Open In App

React Conditional Rendering

Improve
Improve
Like Article
Like
Save
Share
Report

React allows us to conditionally render components which means that the developer can decide which component to render on the screen on on the basis of some predefined conditions. This is known as conditional rendering.

Implementing Conditional Rendering

There may arise a situation when we want to render something based on some condition. For example, consider the situation of handling a login/logout button. Both the buttons have different functions so they will be separate components. Now, the task is if a user is logged in then we will have to render the Logout component to display the logout button and if the user is not logged in then we will have to render the Login component to display the login button.

Conditional rendering in React can be implemented in three ways:

Let us now implement conditional rendering in React using the above mentioned methods:

1. Conditional Rendering using if-else Statement

We can create two components and create a boolean variable which decides the element to be rendered on the screen.

if-else Conditional Rendering Syntax:

function MainComponent(props) {
const myBool = props.myBool;
if (myBool) {
return <Component1/>;
} else{
return <Component2/>;
}
}

if-else Statement Example:

Open your react project directory and edit the Index.js file from src folder:

javascript




import React from "react";
import ReactDOM from "react-dom";
 
// Message Component
// Message Component
function Message(props)
{
    if (props.isLoggedIn)
        return <h1>Welcome User</h1>;
    else
        return <h1>Please Login</h1>;
}
 
// Login Component
function Login(props) {
    return <button onClick={props.clickFunc}>Login</button>;
}
 
// Logout Component
function Logout(props) {
    return <button onClick={props.clickFunc}>Logout</button>;
}
 
// Parent Homepage Component
class Homepage extends React.Component {
    constructor(props) {
        super(props);
 
        this.state = { isLoggedIn: false };
 
        this.ifLoginClicked = this.ifLoginClicked.bind(this);
        this.ifLogoutClicked = this.ifLogoutClicked.bind(this);
    }
 
    ifLoginClicked() {
        this.setState({ isLoggedIn: true });
    }
 
    ifLogoutClicked() {
        this.setState({ isLoggedIn: false });
    }
 
    render() {
        return (
            <div>
                <Message isLoggedIn={this.state.isLoggedIn} />
                {this.state.isLoggedIn ? (
                    <Logout clickFunc={this.ifLogoutClicked} />
                ) : (
                    <Login clickFunc={this.ifLoginClicked} />
                )}
            </div>
        );
    }
}
 
ReactDOM.render(<Homepage />, document.getElementById("root"));


Output:  

Conditional Rendering using if-else example

Explanation:

In the above output, you can see that on clicking the Login button the message and button get’s changed and vice versa.

2. Conditional Rendering using logical && operator

We can use the logical && operator along with some condition to decide what will appear in output based on whether the condition evaluates to true or false. Below is the syntax of using the logical && operator with conditions: 

logical && operator Syntax: 

{
condition &&

// This section will contain
// elements you want to return
// that will be a part of output
}

If the condition provided in the above syntax evaluates to True then the elements right after the && operator will be a part of the output and if the condition evaluates to false then the code within the curly braces will not appear in the output.

logical && operator Example:

Below example is used to illustrate the above mentioned approach Open your react project directory and edit the Index.js file from src folder:

javascript




import React from 'react';
import ReactDOM from 'react-dom';
 
// Example Component
function Example(){
    const counter = 5;
    return(<div>
            {
                (counter==5) &&
                <h1>Hello World!</h1>
            }
           </div>
        );
}
ReactDOM.render(
    <Example />,
    document.getElementById('root')
);


Output:  

Conditional Rendering using logical && Operator Example - output

Explanation:

You can clearly see in the above output that as the condition (counter == 5) evaluates to true so the <h1> element is successfully rendered on the screen.

3. Conditional Rendering using ternary operator

In JavaScript we have a short syntax for writing the if-else conditions due to which the code becomes shorter and easy to read. If the boolean returns true then the element on left will be rendered otherwise element on the right will be rendered

Ternary Operator Syntax:

function MainComponent(props) {
const myBool = props.myBool;
return(
<>
{myBool? <Component 1/>: <Component 2/>}
</>
)
}

Ternary Operator Example:

We will modify the first approach and render the elements using ternary operator

Javascript




import React from "react";
import ReactDOM from "react-dom";
 
// Message Component
function Message(props) {
    return props.isLoggedIn ? <h1>Welcome User</h1> : <h1>Please Login</h1>;
}
 
// Login Component
function Login(props) {
    return <button onClick={props.clickFunc}>Login</button>;
}
 
// Logout Component
function Logout(props) {
    return <button onClick={props.clickFunc}>Logout</button>;
}
 
// Parent Homepage Component
class Homepage extends React.Component {
    constructor(props) {
        super(props);
 
        this.state = { isLoggedIn: false };
 
        this.ifLoginClicked = this.ifLoginClicked.bind(this);
        this.ifLogoutClicked = this.ifLogoutClicked.bind(this);
    }
 
    ifLoginClicked() {
        this.setState({ isLoggedIn: true });
    }
 
    ifLogoutClicked() {
        this.setState({ isLoggedIn: false });
    }
 
    render() {
        return (
            <div>
                <Message isLoggedIn={this.state.isLoggedIn} />
                {this.state.isLoggedIn ? (
                    <Logout clickFunc={this.ifLogoutClicked} />
                ) : (
                    <Login clickFunc={this.ifLoginClicked} />
                )}
            </div>
        );
    }
}
 
ReactDOM.render(<Homepage />, document.getElementById("root"));


Output:

Conditional rendering using Ternary Operator Example - output

Preventing Component from Rendering

It might happen sometimes that we may not want some components to render. To prevent a component from rendering we will have to return null as its rendering output. Consider the below example: 

Rendering Prevention Example:

Open your react project directory and edit the Index.js file from src folder:

javascript




import React from 'react';
import ReactDOM from 'react-dom';
 
// Example Component
function Example(props)
{
    if(!props.toDisplay)
        return null;
    else
        return <h1>Component is rendered</h1>;
}
 
ReactDOM.render(
    <div>
        <Example toDisplay = {true} />
        <Example toDisplay = {false} />
    </div>,
    document.getElementById('root')
);


Output:  

Prevent component rendering example  - output

Explanation:

You can clearly see in the above output that the Example component is rendered twice but the <h1> element is rendered only once as on the second render of the Example component, null is returned as its rendering output.
 



Last Updated : 01 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads