React Lists

Lists are used to display data in an ordered format and mainly used to display menus on websites. In React, Lists can be created in a similar way as we create lists in JavaScript. Let us see how we transform Lists in regular JavaScript.

The map() function is used for traversing the lists. In the below example, the map() function takes an array of numbers and multiply their values with 5. We assign the new array returned by map() to the variable multiplyNums and log it.

Example

 
  1. var numbers = [12345];   
  2. const multiplyNums = numbers.map((number)=>{   
  3.     return (number * 5);   
  4. });   
  5. console.log(multiplyNums);   

Output

The above JavaScript code will log the output on the console. The output of the code is given below.

[5, 10, 15, 20, 25]

Now, let us see how we create a list in React. To do this, we will use the map() function for traversing the list element, and for updates, we enclosed them between curly braces {}. Finally, we assign the array elements to listItems. Now, include this new list inside <ul> </ul> elements and render it to the DOM.

Example

 
  1. import React from ‘react’;   
  2. import ReactDOM from ‘react-dom’;   
  3.   
  4. const myList = [‘Peter’‘Sachin’‘Kevin’‘Dhoni’‘Alisa’];   
  5. const listItems = myList.map((myList)=>{   
  6.     return <li>{myList}</li>;   
  7. });   
  8. ReactDOM.render(   
  9.     <ul> {listItems} </ul>,   
  10.     document.getElementById(‘app’)   
  11. );   
  12. export default App;  

Output

React Lists

Rendering Lists inside components

In the previous example, we had directly rendered the list to the DOM. But it is not a good practice to render lists in React. In React, we had already seen that everything is built as individual components. Hence, we would need to render lists inside a component. We can understand it in the following code.

Example

 
  1. import React from ‘react’;   
  2. import ReactDOM from ‘react-dom’;   
  3.   
  4. function NameList(props) {  
  5.   const myLists = props.myLists;  
  6.   const listItems = myLists.map((myList) =>  
  7.     <li>{myList}</li>  
  8.   );  
  9.   return (  
  10.     <div>  
  11.         <h2>Rendering Lists inside component</h2>  
  12.               <ul>{listItems}</ul>  
  13.     </div>  
  14.   );  
  15. }  
  16. const myLists = [‘Peter’‘Sachin’‘Kevin’‘Dhoni’‘Alisa’];   
  17. ReactDOM.render(  
  18.   <NameList myLists={myLists} />,  
  19.   document.getElementById(‘app’)  
  20. );  
  21. export default App;  

Output

React Lists