How to Map Array to Components in React jS?

React Map Array to Components

When you are developing an app in React you often need to store data in an array of objects. You can display or create all the items in your list using the map() method. In this article, we’ll see how to map the array to components in React js. We’ll also explore how to pass a list of items React components using props.

What is an array of objects?

Before you learn about the map() higher-order function,  you need to know what is an array of objects. Because we use the map() function to extract the values ​​from it. If an array contains objects, it is called an array of objects.
As you know, we store objects as key-value pairs, like:
const Obj = {
          id:1, 
          name: "John", 
          age: 19, 
          address: "banglore, India"
          }
We can access each of these values ​​using the dot operator like this:
console.log(arrObj.name)  // John
console.log(arrObj.age)    // 19
The Array contains a list of elements in the same data types separated by a comma. This means we cannot store strings and numbers in an array, so our values ​​must be in the same data type. As you know, we can store elements in an array within the square brackets, like:
const Arr = ["Red", "Blue", "Green", "White"]
console.log(Arr[0])  // Red
console.log(Arr[2])    // Green
Note that: When we access the values ​​in the array, the index value of the first element is 0, so remember that the array index starts from 0.
If both are combined and we put the objects in an array then it is called an array of objects. We will use it to store important data in React. For example, it can be used to store the details of all employees in a company. Here is the syntax for creating an array of objects
const employee = [ {key1:values1 },  {key2:values2}, {key3:values3}... {keyN:valuesN}]
In this syntax, we put square braces to mention the array, and inside the array we’ve created objects for each element.
Note that: A comma must be placed between each key-value pair inside objects, and a comma must be placed between each array element outside objects. And you must give the same key name to all objects, which must be unique names. We should create a key “id”, which specifies the unique number of an object. If two objects have the same key and values ​​we can identify them using the id key.
Here’s an example of how the company stores our employee details in an array of objects.
const company = [
        {id:1, name: "John",  age: 19 },
        {id:2, name: "Steve", age: 39 },
        {id:3, name: "Roy",   age: 28 },
        {id:4, name: "Smith", age: 24 }
     ]
So let’s assume that a company has stored the details of all their employees like the above code. To find out how old “Steve” is, we need to use both square braces and the dot operator like:
console.log("Name : " + company[1].name)  
console.log("Age : " + company[1].age)
Name : Steve
Age : 39
But we cannot use this method to display the names and ages of all the employees in the company, so we use the map() function. So let’s see how to use the map() function in react

What is the map() function and how to use it?

In react, you can access each element of an array into a React component using the map() function. You have to pass a callback function as a parameter to the map() function, which is be executed for each item in the array.
Here’s an example to list a name and age of all employees using the map() function
import React, { Component } from "react";

const company = [
  {id:1, name: "John",  age: 19 },
  {id:2, name: "Steve", age: 39 },
  {id:3, name: "Roy",   age: 28 },
  {id:4, name: "Smith", age: 24 }
 ]


function data(item){
  return <p key={item.id}>Name = {item.name}, Age = {item.age} </p>
   }

class App extends Component {
  render() {
    return (
      <div className='App'>
         {company.map(data)}
    </div> 
    );
  }
}


export default App;
In the above example code, we have pass the function called ‘data’ inside the map() function. In the data function, we take a parameter called item and return {item.name} and {item.age} so it displays the name and corresponding age of each object. The key attribute is crucial for React’s internal reconciliation algorithm, and it should be a unique identifier for each component.
Instead of writing the function separately and passing it as a parameter to the map() function, you can create a function directly inside the map() function like this:
class App extends Component {
  render() {
    return (
      <div className='App'>
      {company.map(item => 
        <div key={item.id}>
      {item.name} = {item.age}
        </div>
      )}
    </div>
    );
  }
}

How to pass an array of objects using props?

In this example, we have created an array of objects in the parent component ie App component, and pass it to ‘itemList‘ component through props. Then we passed each item from ‘itemList‘ to ‘ItemComponent’ using the map() function and displayed title and description in an array of objects.
App.js
import React from 'react';
import ItemList from './ItemList';


const App = () => {
  // Example data for the array of items
  const items = [
    { id: 1, title: 'Item 1', description: 'Description for Item 1' },
    { id: 2, title: 'Item 2', description: 'Description for Item 2' },
    { id: 3, title: 'Item 3', description: 'Description for Item 3' },
  ];


  return (
    <div>
      <h1>Items List</h1>
      <ItemList items={items} />
    </div>
  );
};


export default App;
ItemList.js
const ItemList = ({ items }) => {
  return (
    <div>
      {items.map((item) => (
        <ItemComponent key={item.id} item={item} />
      ))}
    </div>
  );
};


export default ItemList;
ItemComponent.js
import React from 'react';


const ItemComponent = ({ item }) => {
  return (
    <div>
       <p> {item.title}</p>
       <p>{item.description}</p>
    </div>
  );
};


export default ItemComponent;
Our Expected Output:
Item 1 Description for Item 1
Item 2 Description for Item 2
Item 3 Description for Item 3

Why do we have to pass key attributes?

It’s important to note that the key attribute should be a stable, unique identifier for each element in the list. In most cases, an ID from the data itself, such as a database ID or a unique identifier, is a good choice for the key. The key should remain consistent across re-renders, and it should not be generated randomly or based on the component’s internal state, as this can lead to unnecessary re-renders.

READ ALSO  A Great Example to Understand the Usage of ReactJS Props

Leave a Reply