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 as we create the list in JavaScript.

The map() function is used to traverse the list. Let’s understand it with an example to see how we traverse the list in JavaScript. In the following example, we are using the map() function, which is taking an array of numbers and divides its value by 5.

The new array which is returned by the map() function is assigned to the variable named as final.

Example:

In JavaScript

 

Output:

After the successful compilation of the above code, you will get the following output:

React Lists

Now, let us understand the creation and traversing the list in React. For traversing the list, we will again use the map() function. At last, we will assign the array elements to the new variable final. After that we include this new list inside the <ul></ul> element.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
const list = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa']; 
const final = list.map((list)=>{ 
return 
  • {list}
  • ; }); ReactDOM.render(
      {final}
    , document.getElementById('app') ); export default App;

    Output:

    React Lists example

    Rendering Lists Inside Components

    The approach applied in the previous example is not a good practice for rendering the list in React because we had directly rendered the list to the DOM. We had already seen that, in React, everything is built as individual components. So, we require rendering the lists in a component.

    For example:

    import React from 'react'; 
     import ReactDOM from 'react-dom'; 
     function ListExample(props) { 
      const lists = props.lists; 
      const final = lists.map((lists) => 
      
  • {lists}
  • ); return (

    Rendering Lists inside component

      {final}
    ); } const lists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa']; ReactDOM.render( , document.getElementById('app') ); export default App;

    Output:

    Rendering Lists Inside Components



    ADVERTISEMENT
    ADVERTISEMENT