×

React Conditional Rendering

React Conditional Rendering

In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React component updates the UI to match them.

There are several ways to do Conditional Rendering in React that are as follows:

  • If
  • Ternary operator
  • Logical && operator
  • Switch case operator
  • Conditional Rendering with enums

if

It is the simplest way to do a conditional rendering in React. It does not apply to the total block of the component. If the condition is true, it will return the rendered element. It can be clear with the following example:

Example:

function UserLogin(props) { 
  return 

Hello World!!

; } function GuestLogin(props) { return

Sign Up First.

; } function SignUp(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return ; } return ; } ReactDOM.render( , document.getElementById('root') );

Logical && Operator

It is a Logical && (AND) operator, which is also used for condition check. If you are using it with if operator, then it checks both conditions, i.e., if the first condition will true, then it will check the second condition, but if the first condition is false, then it will skip the second condition. It happens because AND (&&) operator will give you the output only when both of the conditions are true.

If you are not using it with if the operator and treat the second statement as an output statement, then, you will only get the output when your first conditional statement is true. If your conditional statement is false, then it will skip your second statement.

Example:                                                                                                                                                     

The following example will show you the use of && (AND) operator with if operator:

import React from 'react'; 
import ReactDOM from 'react-dom'; 
class App extends React.Component
{
render()
{ if((10 > 5) && (5>4))
{
return(

Hello

); } } } export default App;

Output:

Logical && Operator

Another example of AND (&&) operator in which the second statement works as output statement:

import React from 'react'; 
import ReactDOM from 'react-dom';   
class App extends React.Component
{
render()
{ 
return(<div>   
{   
(8 > 4) && alert('!!!! Hello World !!!!')  
}   
</div>   
);   
}
}  
export default App; 

Output:

example of AND (&&) operator

Ternary Operator

This operator makes the if-else statement much brief. This ternary operator is used when two alternate blocks give a particular condition.

The syntax of the ternary operator is as follows:

Syntax:

condition ? true : false 

If the condition is true, then statement1 (true statement) will beconsidered as a result, but if the condition is false, then the statement2 (false statement) will be considered as a result.

It will be clear will the following example:

Example:

  • When the condition is true, it will render statement1.
import React from 'react';
import ReactDOM from 'react-dom'; 
class App extends React.Component
{
render()
{
return (

{10>5 ? 'Condition is True' : 'Condition is False'}.

); } } export default App;

                Output:

Ternary Operator
  • When the condition is false, then it will render statement2.
import React from 'react'; 
import ReactDOM from 'react-dom'; 
class App extends React.Component
{
render()
{ 
return ( 

{10<5 ? 'Condition is True' : 'Condition is False'}.

); } } export default App;

Output:

When the condition is false

Switch case Operator

This operator is used when you have multiple conditional renderings.

The example of switch case is as follows:

Example:

import React from 'react';
import ReactDOM from 'react-dom'; 
class App extends React.Component
{
render()
{ 
var i=2; 
switch(i) 
{ 
case 0: 
return 

Sunday

; case 1: return

Monday

; case 2: return

Tuesday

; case 3: return

Wednesday

; case 4: return

Thursday

; case 5: return

Friday

; case 6: return

Saturday

; default: return null; } } } export default App;

Output:

Switch case Operator

Conditional Rendering with Enums

Enums is the short word for ‘enumerations,' and a right way for the multiple conditional rendering. It provides more readability than the switch-case operator. It is a suitable option for mapping between different states and also mapping in more than one condition.

Example:

function NotificationMsg({ text, state }) { 
  return ( 
  
{{ info: , warning: , }[state]}
); }

Example of Conditional Rendering

The below example will show you the use of conditional rendering.

Example:

import React, { Component } from 'react';
 // Message Component 
 function Message(props) 
 { 
  if (props.isClicked) 
  return 

!!!! Hello World !!!!

; else return

!!! It is an example of Conditional Rendering in React!!!

; } // Click Component function Click(props) { return(
); } // Clicked Component function Clicked(props) { return(
); } class App extends Component{ constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleClicked = this.handleClicked.bind(this); this.state = {isClicked : false}; } handleClick() { this.setState({isClicked : true}); } handleClicked() { this.setState({isClicked : false}); } render(){ return(

Conditional Rendering Example

{ (this.state.isClicked)?( ) : ( ) }
); } } export default App;

Output:

Once the above code gets successfully compiled, you will get the following output:

Example of Conditional Rendering

After clicking the button, you will get the following output:

use of conditional rendering.

Related Topics

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.

React Portals

React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

3 minutes read.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.