Conditional Rendering And List Rendering In React

Introduction

 
In the previous article, we reviewed about binding event handler in React and using a method as property in React. In this article, we will learn about conditional rendering and how we can define conditions in React. Also, we will see how a list can be rendered in React.
 

Conditional Rendering

 
There are 5 ways we can define conditional rendering.
  1. If/Else
  2. Element Variables
  3. Ternary Operator
  4. Short-circuit operator
  5. Immediately - Invoked Function Expressions (IIFE).
If/Else Condition
 
The If/Else condition is the easiest way to specify conditional statements. The syntax is the same as in JavaScript despite the fact that for each if/else statement, a return statement needs to be defined which makes the code repetitive and not easy to read and modify.
 
For example, look at this code.
  1. import React from 'react';    
  2. class ConditionalRendering extends React.Component{    
  3.        constructor(props){    
  4.            super(props);    
  5.            this.state ={    
  6.                IsLoggedIn : false    
  7.            }    
  8.         }    
  9.     
  10.        render(){    
  11.           if(this.state.IsLoggedIn){    
  12.                return <div>Welcome User </div>    
  13.           }    
  14.           else{    
  15.               return <div>You need to login</div>    
  16.           }    
  17.     };    
  18. }    
  19. export default ConditionalRendering;  
The output will be displayed as below,
 
Conditional Rendering And List Rendering In React
 
After changing the IsLogged : true, the output will be slightly different.
 
Conditional Rendering And List Rendering In React
 
As seen in the above example, the return statement is defined every time for each if and else. This is just a demo example so it just includes 2 statements. However, the most common mistake is having multiple if/else statements and various return statements; which makes React to refresh the entire DOM when any condition is updated.
 
In short, React applications should not have multiple return statements in the render() method. So, to resolve this issue, either use embedded JSX expressions or variable assignment for achieving performance optimization.
 
As in the previous article, we have defined that React performs a search from top to bottom and after signifying changes in the component tree, updates only that part, so it is appropriate to use a proper conditional statement that helps React to evaluate properly. Now, look at the second approach.
 
Element Variables
 
The solution of repeating return statement in render() method is Element Variable. This approach uses a JSX variable that stores values when the condition returns true. And that variable is then used while displaying data.
 
For Example,
  1. import React from 'react';    
  2. class ConditionalRendering extends React.Component{    
  3.        constructor(props){    
  4.              super(props);    
  5.             this.state ={    
  6.                  IsLoggedIn : true    
  7.             }    
  8.         }    
  9.     
  10.       render(){    
  11.             let message;     
  12.            if(this.state.IsLoggedIn){    
  13.                 message = <div>Welcome User </div>;    
  14.            }    
  15.           else{     
  16.                message = <div>You need to login</div>;    
  17.           }    
  18.     
  19.         return message;    
  20.      };    
  21. }    
  22. export default ConditionalRendering;    
The output for the above code is as below.
 
Conditional Rendering And List Rendering In React
 
The main render() method has only 1 return statement but it is not necessary to use if-else blocks. We have another approach to simplifying this.
 
Ternary operator
 
Despite using if/else multiple block statements, we can use Ternary conditional operator. That includes:
  1. Condition? Expr_if_true : expr_if_false;  
The operator is wrapped in curly braces and the expression can contain JSX, optionally wrapped in parentheses to improve readability and can be applied in different parts of the component.
 
For example,
  1. import React from 'react';    
  2. class ConditionalRendering extends React.Component{    
  3.        constructor(props){    
  4.             super(props);    
  5.             this.state ={    
  6.                         IsLoggedIn : true    
  7.             }    
  8.       }    
  9.           
  10.       render(){    
  11.             return this.state.IsLoggedIn? <div> Welcome User</div> : "";    
  12.       };    
  13. }    
  14. export default ConditionalRendering;   
The output for example will be displayed the same as above.
 
Conditional Rendering And List Rendering In React
 
Short-circuit operator
 
This operator is the extended version of the short circuit operator. It is a special case and simplified version of the Ternary operator which uses && operator.
 
It is not like the & operator which evaluates the right side expression first. The && operator evaluates the left side expression and evaluates the result.
 
So, if the statement includes false && expr, it will not evaluate expr as the statement always returns false.
 
For example,
  1. import React from 'react';    
  2. class ConditionalRendering extends React.Component{    
  3.        constructor(props){    
  4.               super(props);    
  5.               this.state ={    
  6.                      IsLoggedIn : true    
  7.               }    
  8.        }    
  9.            
  10.        render(){    
  11.               return this.state.IsLoggedIn && <div> Welcome User</div>;    
  12.         };    
  13. }    
  14. export default ConditionalRendering;  
The output will be displayed as below.
 
Conditional Rendering And List Rendering In React
 
By changing the value of IsLoggedIn to false, the output will not display anything.
  1. this.state ={    
  2.       IsLoggedIn : false    
  3. }   
Conditional Rendering And List Rendering In React
 
These techniques are used when we are not having multiple nested statements, for such purpose React provides another approach named Immediately-Invoked function expressions(IIFE).
 
Immediately-Invoked function expressions (IIFE)
 
As the name itself suggests, IIFE is the functions that are executed itself as soon as it is defined.
 
As in the below syntax it is defined and used.
  1. function TestFunc(){    
  2. }    
  3. TestFunc();    
But if we need  to execute function as soon as it's defined:
  1. (function TestFunc(/*args*/){    
  2. }(/*args*/));   
Or
  1. (function TestFunc(/*args*/){    
  2. })(/*args*/);   
Or we can use the arrow function:
  1. ((/*args */) => {    
  2. })(/* args */)   
In React, curly braces are used to use any of the above conditional statements and return based on user output.
 
List Rendering
 
In React, List array can have many ways to display in the browser, we will go for each type step by step. Let’s start with the first approach.
 
Using array index
 
List items can be displayed in the browser using the array index, but this approach becomes quite tedious as it includes code repetition and if the number of array is large then this is not a good approach.
 
For example:
  1. import React from 'react';    
  2.     
  3. function EmployeeList(){    
  4.           const employee = ['zbc','xyz'];    
  5.               return(    
  6.                   <div>    
  7.                             <h2>{employee[0]}</h2>    
  8.                             <h2>{employee[1]}</h2>     
  9.                   </div>    
  10.          )    
  11. }    
  12. export default EmployeeList;  
The output will be displayed as below
 
Conditional Rendering And List Rendering In React
 
This approach uses code repetition so there is another approach named Array.map()
 
Array.map()
 
This function is used to display data from a list in an easy manner. This way provides easy readability and understandability.
 
Syntax - Array.map(name => {name})
 
For example,
  1. import React from 'react';      
  2. function EmployeeList(){    
  3.       const employee = ['abc','xyz'];    
  4.          
  5.       return(    
  6.           <div> {employee.map(emp => <h2>{emp}</h2>)} </div>    
  7.        )    
  8. }    
  9. export default EmployeeList;  
The output will be same for the above example
 
Conditional Rendering And List Rendering In React
 
Now this can also be normalized by storing array list in the variable,
  1. import React from 'react';      
  2. function EmployeeList(){    
  3.        const employee = ['abc','xyz'];    
  4.        const employeeList = employee.map(emp => <h2>{emp}</h2>);    
  5.          
  6.       return(    
  7.              <div>{employeeList}</div>    
  8.        )    
  9. }      
  10. export default EmployeeList;   
The output will be the same as above but the code provides better readability.
 
Conditional Rendering And List Rendering In React
 
The above codes are simple concepts, having only 1 list item. Now we will see complex examples of having an array with key-value pair in each array having multiple values.
 
For example:
  1. import React from 'react';    
  2. function EmployeeList(){    
  3.        const employee = [{    
  4.             name:'abc',    
  5.             salary:'50$',    
  6.             position:'Jr. Developer'    
  7.        },{    
  8.             name:'xyz',    
  9.             salary:'100$',    
  10.             position:'Sr. Developer'    
  11.        },{    
  12.             name:'mno',    
  13.             salary:'150$',    
  14.             position:'Project Manager'    
  15.        }    
  16.      ];    
  17.     
  18.       const employeeList = employee.map(emp => <h2>My name is    {emp.name} working as {emp.position} and having salary {emp.salary}     </h2>);    
  19.          
  20.        return(    
  21.             <div>    
  22.                         {employeeList}    
  23.             </div>    
  24.        )    
  25. }      
  26. export default EmployeeList;   
The output will be displayed as,
 
Conditional Rendering And List Rendering In React
 
Now let's talk about moving the array concept to subcomponent and calling that component in main component.
 
Create a subcomponent having function that will return html:
  1. import React from 'react';    
  2. function Employees({emp}){    
  3.        return(    
  4.        <div>    
  5.               <h2>My name is {emp.name} working as {emp.position} and having salary {emp.salary} </h2>    
  6.        </div>    
  7.        )    
  8. }    
  9. export default Employees;  
Now import this component in parent component
  1. import React from 'react';    
  2. import Employees from './Employees';    
  3. function EmployeeList(){    
  4.         const employee = [{    
  5.               name:'abc',    
  6.               salary:'50$',    
  7.               position:'Jr. Developer'    
  8.           },{    
  9.               name:'xyz',    
  10.               salary:'100$',    
  11.               position:'Sr. Developer'    
  12.           },{    
  13.               name:'mno',    
  14.               salary:'150$',    
  15.               position:'Project Manager'    
  16.           }    
  17.        ];    
  18.      
  19.         const employeeList = employee.map(emp =>    
  20.               <Employees emp={emp}></Employees>    
  21.               );    
  22.               return <div>{employeeList}</div>;    
  23. }    
  24. export default EmployeeList;    
The output for the above will be displayed as below
 
Conditional Rendering And List Rendering In React
 
Now look at the console in browser where there are errors related to keys:
 
Conditional Rendering And List Rendering In React
 
It will show aa warning related to keys as each child in a list should have a unique key prop. This error can be resolved by defining the key to each list item generated using JSX. The key defined should not be the same for any list item.
 
Now as in the previous example add key property to EmployeeList component,
  1. import React from 'react';    
  2. import Employees from './Employees';    
  3. function EmployeeList(){    
  4.          const employee = [{    
  5.                   id:1,    
  6.                   name:'abc',    
  7.                   salary:'50$',    
  8.                   position:'Jr. Developer'    
  9.             },{    
  10.                   id:2,    
  11.                   name:'xyz',    
  12.                   salary:'100$',    
  13.                   position:'Sr. Developer'    
  14.            },{    
  15.                   id:3,    
  16.                   name:'mno',    
  17.                   salary:'150$',    
  18.                   position:'Project Manager'    
  19.          }    
  20.       ];    
  21.          const employeeList = employee.map(emp => <Employees key= {emp.id} emp={emp}></Employees>);    
  22.          return <div>{employeeList}</div>;     
  23.      }    
  24.     
  25. export default EmployeeList;  
Now, check the result in the browser.
 
Conditional Rendering And List Rendering In React
 
Now we can see there is no warning in the console. The key prop can contain anything from the list that we know is unique.
 
The important point that needs to be kept in mind when using key prop is that key prop cannot be used in child component, for example, if we access key prop from EmployeeList component in Employee Component,
  1. import React from 'react';      
  2. function Employees({emp,key}){    
  3.        return(    
  4.               <div>    
  5.                      <h2>{key} My name is {emp.name} working as {emp.position} and having salary {emp.salary} </h2>    
  6.               </div>    
  7.        )    
  8. }    
  9. export default Employees;  
The output will be displayed as below,
 
Conditional Rendering And List Rendering In React
 
The warning in console itself suggests that key is undefined when passed from parent component to child component.
 
Now here the important point is why do we need key props. The key props are used to identify item lists on that key and to append, remove or insert list item from the lists.
 
Importance of key prop,
  • Key prop helps to easily identify which item is added, updated or removed.
  • Key prop helps in updating user interface efficiently.
  • Keys provide stable identity to elements..
Now let’s move further and see what if we have a simple array which doesn’t have any attribute name, id for example ,
  1. const cities = ['surat','vadodara','mumbai'];    
  2. const cityList = cities.map(city => <h2 key={city}>{city}</h2>);    
  3. return <div>{cityList}</div>;    
The output will be displayed as below
 
Conditional Rendering And List Rendering In React
 
Now, the key is defined based on the values of the list. Now what if the values in the array have repeating values, then it will throw a warning for keys to be unique.
 
Updated list:
  1. const cities = ['surat','vadodara','mumbai','surat'];  
The output will be shown as below
 
Conditional Rendering And List Rendering In React
 
So in that case we should use index as key for array values. The map function accept 2 parameters , map(value,index).
 
For example,
  1. const cities = ['surat','vadodara','mumbai','surat'];    
  2. const cityList = cities.map((city,index) => <h2 key={index}>{city}</h2>);    
  3. return <div>{cityList}</div>;  
Now the output will be displayed as below without warning,
 
Conditional Rendering And List Rendering In React
 
In React, index starts from 0 as shown below,
  1. const cities = ['surat','vadodara','mumbai','surat'];    
  2. const cityList = cities.map((city,index) => <h2 key={index}>{index} {city}</h2>);    
  3. return <div>{cityList}</div>;     
After defining index as key the ouput will be displayed as below,
 
Conditional Rendering And List Rendering In React
  

When should index be used as a key?

 
It is not valid to always use index as a key as it may result in UI issues. So following are the points where index should be used as key:
  • The items in the list don’t have a unique id.
  • The list is static and that is not going to change.
  • The list is not going to filter or sort.
When all the above 3 conditions are fulfilled by the list then the index can be used as a key in the list. 
 

Conclusion

 
In this article, we learned Conditional Rendering and List rendering in React applications, and in how many ways we can use Array.Map() to display list data. In the next article, we will learn about Styling and CSS basics usage in React and get an  introduction to the Form concept.
 
Next in this series >> Styling And CSS in React 
Author
Priyanka Jain
0 9.6k 872k
Next » Styling And CSS In React