ReactJS | Conditional Rendering

22 Jan, 2021
We have discussed how to create components, how to render components, using proptypes, using states to store information, and much more. In our previous articles, we had also developed a basic Calculator Application in ReactJS. 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. This is what we call Conditional Rendering in ReactJS. That is to create multiple components and render them based on some conditions. This is also a kind of encapsulation supported by React. Let us now create a page in React which will have a Message and a Button. The button will read “Login” if the user is not logged in and “Logout” if the user is logged in. We will also add some functionality to this button as upon clicking “Login” the message will read “Welcome User” and the button will change to “Logout” and upon clicking “Logout” the message will change to “Please Login” and the button will change to “Login”.To do this, we will create a parent component named “Homepage”, two components named “Login” and “Logout” and one more component named “Message”. We will use a state variable named “isLoggedIn” to store the information about whether the user is logged in or not. The value of this variable will change according to the click of the button by the user. The Homepage component will render the Message component to display the message and it will also render one of the components among Login and Logout based on the value stored in isLoggedIn. The Message component will also return different messages based on the value of state isLoggedIn.Let us now look at the complete program to do the above task: 
Open your react project directory and edit the Index.js file from src folder:
src index.js: 
javascript
import React from 'react';import ReactDOM from 'react-dom'; // Message Componentfunction Message(props){    if (props.isLoggedIn)        return <h1>Welcome User</h1>;    else        return <h1>Please Login</h1>;} // Login Componentfunction Login(props){   return(           <button onClick = {props.clickFunc}>               Login           </button>       );} // Logout Componentfunction Logout(props){    return(           <button onClick = {props.clickFunc}>               Logout           </button>       );} // Parent Homepage Componentclass 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:  
In the above output, you can see that on clicking the Login button the message and button get’s changed and vice versa. 
Using conditions with 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:  
{
    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.Below example is used to illustrate this: Open your react project directory and edit the Index.js file from src folder:
src index.js:
javascript
import React from 'react';import ReactDOM from 'react-dom'; // Example Componentfunction Example(){    const counter = 5;     return(<div>            {                (counter==5) &&                <h1>Hello World!</h1>            }           </div>        );} ReactDOM.render(    <Example />,    document.getElementById('root'));
Output:  
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. 
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: Open your react project directory and edit the Index.js file from src folder:
src index.js:
javascript
import React from 'react';import ReactDOM from 'react-dom'; // Example Componentfunction 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:  
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. 
shubhamyadav4
JavaScript-Misc
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?