List And Mapping In React

In this List And Mapping In React tutorial, we will learn about the list and key feature of JavaScript and how they are used in React. As we know the general definition of the list, the list is a collection of objects like a shopping list, a list of tourists, etc.

We will study the data in the list and how to use it.

What is List?

We already saw the general definition of the list, now in the list of the technical terms is the collection of objects of similar/different type. We can define a list in JavaScript like

Syntax:-

list = [
  {
    name:"abc",
    designation:"Web developer",
    timing:8
  },
  {
    name:"efg",
    designation:"Android developer",
    timing:9
  }
]

Why we use a list in React?

=> We use the list function to iterate through the list as the id/key property is unique to each object in the list.

=>Every time the list render it render according to the list. Hence if we update the list or even in production case we update the database we shouldn’t be facing the problem of managing the render UI of reacting.

This example will show the use of List and map function.

  • Create a react app and clean it for the use.
  • In App.js file import React and CSS file if any
  • Create a functional component that can be returned JSX
  • Inside that create a JavaScript List and then create an object as a list item.
  • Return JSX and the outer Wrap would be of <div>.
  • Inside that return an un-ordered list <ul> tag of JSX
  • Inside { } write the map function to iterate through the list.
    {list.map((person) => {
             return( <li>Name: {person.name}<br />
              Designation:{person.designation}
              </li>
              )
  • Return a JSX list inside the function call
  • And export App.js file

App.js

import React from 'react';
import './App.css';


const App = () =>{

  const list = [
    {
      name:"abc",
      designation:"Web developer",
      timing:8
    },
    {
      name:"efg",
      designation:"Android developer",
      timing:9
    }
  ]
  
  return(
    <div >
      <ul>
        {list.map((person) => {
         return( <li>Name: {person.name}<br />
          Designation:{person.designation}
          </li>
          )
        })}
      </ul>
    </div> 
  )
 
}

export default  App;

Output