Map() Function in React

Introduction

React, with its declarative and component-based architecture, provides developers with powerful tools for manipulating data. One such tool is the map() function, a versatile method that simplifies the process of iterating over arrays. In this comprehensive guide, we will explore the map() function in-depth, using practical examples to enhance your understanding.

Map Function in React

At its core, the map() function is a fundamental JavaScript method used to create a new array based on an existing one. It iterates over each element in the original array, applies a provided function, and collects the results into a new array. This concise and powerful utility is particularly handy when working with React components and rendering dynamic content.

Sample Array Object: EmployeeDetails

Before delving into React-specific applications, let's introduce a sample array object named EmployeeDetails. Each element in this array represents an employee and includes properties such as ID, name, age, and salary.

const EmployeeDetails=[
{id:1, name:"Mayooran", age:23, salary:25000},
{id:2, name:"Peter", age:22, salary:28000},
{id:3, name:"Anna",age:23, salary:27000},
{id:4, name:"Suren", age:24, salary:28000},
{id:5, name:"Nimmi", age:28, salary:38000}
];

This array will serve as the basis for our practical examples.

Console

Picture 1. In this image, you can see the EmployeeDetails in the Console output. It is an array object 5 elements are there.

Utilizing map() with a Basic Example

Let's start with a simple example to grasp the basic functionality of the map() function. We'll extract the names of the employees from EmployeeDetails using a map().

const EmployeeName = EmployeeDetails.map(employee => employee.name);

In this example, EmployeeName will be an array containing only the names of the employees. This straightforward application of map() showcases its ability to streamline data extraction.

Utilizing map()

Picture 2. EmployeeName will be an array containing only the names of the employees.

Applying map() in a React Component

Now, let's integrate the map() function into a React component named Details. In this component, we will render a list of employee names using the map() function.

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

function App() {

  const EmployeeDetails=[
    {id:1, name:"Mayooran", age:23, salary:25000},
    {id:2, name:"Peter", age:22, salary:28000},
    {id:3, name:"Anna",age:23, salary:27000},
    {id:4, name:"Suren", age:24, salary:28000},
    {id:5, name:"Nimmi", age:28, salary:38000}];
   
   const EmployeeName = EmployeeDetails.map(employee => <li key={employee.id}>{employee.name}</li>)
   return(
      <div>
        <h1> Employees Name </h1>
         <ul>{EmployeeName }</ul>
      </div>
   )
}
export default App;

This React component uses map() to transform the EmployeeDetails array into a list of <li> elements, each displaying a employee's name. The key attribute is crucial for React to efficiently manage dynamic lists.

React App

Picture 3. EmployeeName will be an array containing only the names of the employees in the React app.

Employee salary index

Picture 4. EmployeeDetails console output in the table view.

Now, let's integrate the map() function into a React component with a Table view. In this component, we will use the map() function to render a list of employees.

  1. To incorporate the table view, we are creating an HTML table. Begin by creating a new folder named 'demo' inside the 'src' folder.
  2. Inside the 'demo' folder, create a new file named 'table.jsx' and 'table.css' to define the table page.

React demo

Picture 5.  Inside the 'demo' folder, create table.jsx and table.css.

You can see the table.jsx.

import React from 'react';
import './table.css'; // Import your CSS file


const Table = ({data}) => {

    const columns = Object?.keys(data[0] ? data[0] : data);

  return (
    <div className="table-container">
      <table className="custom-table">
        <thead>
          <tr>
          {columns.map((column, index) => (<th key={index}>{column}</th>))}
          </tr>
        </thead>
        <tbody>
        {data.map((row) => (
          <tr key={row.id}>
          <td>{row.id}</td>
          <td>{row.name}</td>
          <td>{row.age}</td>
          <td>{row.salary}</td>
        </tr>
        ))}
        </tbody>
      </table>
    </div>
  );
};

export default Table;

In the context of a table header name map, let's assume that there is an array of objects called 'data,' with each object having keys representing column names. To gather the column names, you can use the following code.

const columns = Object?.keys(data);

This code will collect the column names and store them in the 'columns' variable."

When mapping column names, you can use the following code snippet.

{columns.map((column, index) => (<th key={index}>{column}</th>))}

This code iterates through the 'columns' array, creating a <th> (table header) element for each column name, with a unique key assigned based on the index.

<tr key={row.id}>: For each element in the data array, a table row (<tr>) is created. 

The key attribute is set to the value of row.id. 

In React, the key is used to uniquely identify each element in a list, helping React to efficiently update and re-render components.

    {data.map((row) => (
          <tr key={row.id}>
          <td>{row.id}</td>
          <td>{row.name}</td>
          <td>{row.age}</td>
          <td>{row.salary}</td>
        </tr>
        ))}

Visualizing the Result

Result

Picture 6. Inside the 'demo' folder, create table.jsx and table.css.

In the accompanying images (refer to Pictures 03 and 06), you can observe the result of applying the map() function. Picture 03 displays the array of employee names generated using map() directly, while picture 06 showcases the rendered list table view within the React component.

Conclusion

Mastering React's map() function empowers you to elegantly handle dynamic data rendering within your components. This guide has provided you with a solid foundation, from the basic principles of map() to its practical implementation in React. As you continue your React journey, explore the diverse applications of the map() function to enhance your development skills.


Adelanka (PVT) LTD
Globally based Software Developing & Data Processing Company