Using map() in JavaScript and React.js

Oct. 5, 2021, 7:21 p.m.
JavaScript React · 5 min read
Using map() in JavaScript and React.js

Introduction

Arrays are the most commonly used data structures in the programming community. An array is a collection of items that store data in a linear way. Every item in an array is stored in a particular index and through these indexes, the array is accessed and manipulated. 

Arrays are an important part of modern frontend development. The data that is processed on the front-end, is usually stored in arrays. Working with arrays can be tough sometimes. So JavaScript has introduced several in-built array methods. Each of these array methods is created to do a particular job. In the end, the main goal is to ease the developer’s job. 

The map() method is one of the most commonly used array methods in JavaScript. It has become an important part of modern development. In this tutorial, we will discuss the map method in JavaScript and how to use it with React.js.

 

Understanding map() in JavaScript

In simple words, the map() method creates a new array from an existing array. Basically, the map() method executes a function for every item of the array. The new array contains the items returned from this function. 

Let’s understand the map() method with the help of a simple example.

let arr = [10, 20, 30, 40, 50];

let newArr = arr.map((item) => {

   return item * 2;

});

console.log(newArr);

In the above code, the map() method is used to create a new array from the given array named “arr”. Every item of the “arr” is being processed by the function one by one to return its double value. 

 

Output:

JavaScript Map Array

 

The function executed by map() has a second optional argument. This is the index of the current element being iterated by the map() method.

let arr = [10, 20, 30, 40, 50];

let newArr = arr.map((item, i) => {

  console.log(`Index: ${i}`);

  return item * 2;

});

console.log(newArr);

 

Output: 

JavaScript Map Array Index

 

More commonly, the map() method is used with an array of objects. 

let employees = [
  {
    id: 001,
    name: "Tommy",
    age: 23,
    city: "New York",
  },

  {
    id: 002,
    name: "Mike",
    age: 27,
    city: "Detroit",
  },

  {
    id: 003,
    name: "Lisa",
    age: 25,
    city: "Chicago",
  },
];

 

Now, suppose we want the “name” from every object. How to do it? By using the map() method to create a new array that will contain the value of “name” for every object. 

let names = employees.map((employee) => {
  return employee.name;
});

 

Output:

JavaScript Map Array of Objects

 

Remember, if no return statement is provided in the map(), it will return undefined for every iteration. 

 

map() in React

As mentioned earlier, the map() method is heavily used in React. The most common use of map() in React is to render a list in one way or another. Let’s understand how to use the map() method in React to render lists on the UI. 

Let’s save the following “employees” array in a separate file named “employees.js”.

let employees = [
  {
    id: 001,
    name: "Tommy",
    age: 23,
    city: "New York",
  },
  {
    id: 002,
    name: "Mike",
    age: 27,
    city: "Detroit",
  },
  {
    id: 003,
    name: "Lisa",
    age: 25,
    city: "Chicago",
  },
  {
    id: 004,
    name: "Kane",
    age: 31,
    city: "New York",
  },
  {
    id: 005,
    name: "Mark",
    age: 37,
    city: "Chicago",
  },
];


export default employees;

We will build a simple React application to display the employee data on the UI using the map() method. 

Observe the following code.

function App() {
  return (
    <div>
      {employees.map((employee) => {
        const list = (
          <>
            <ul>
              <li>Id: {employee.id}</li>
              <li>Name: {employee.name}</li>
              <li>Age: {employee.age}</li>
              <li>City: {employee.city}</li>
            </ul>
            <hr />
          </>
        );
        return list;
      })}
    </div>
  );
}

Earlier, the function inside the map() method was returning data types such as numbers and strings. But in React, the function can return JSX elements, as it is done in the above code.

employees.map((employee) => {
  const list = (
    <>
      <ul>
        <li>Id: {employee.id}</li>
        <li>Name: {employee.name}</li>
        <li>Age: {employee.age}</li>
        <li>City: {employee.city}</li>
      </ul>
      <hr />
    </>
  );
  return list;
});

For every item of the “employees” array, the map() is returning an unordered list with <hr /> tag. 

This map() is placed inside the returning statement of the “App” component, meaning it will display the values returned by the map on the UI. 

React Map Array Of Objects

  

So, we are not creating a new array here. Instead, we are rendering every returned value from the map() method in the UI. This is the basic use of the map() method in React. 

We can also create dynamic lists using the map() method. Observe the following UI. 

React dynamic lists input

Suppose, we want the text added in the input field to be listed below when the button is clicked. This is where the map() method comes in to create dynamic lists. 

Observe the following code.

function App() {
  const [data, setData] = useState([]);
  const [input, setInput] = useState("");


  const clickHandler = () => {
    const tempData = data;
    tempData.push(input);
    setData(data);
    setInput("");
    console.log(data);
  };



  return (
    <div className="App">
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />{" "}
      <button onClick={clickHandler}>Add</button>
      <hr />
    </div>
  );
}

export default App;

In the above code, whenever the button is clicked, the text in the input field will be added into the “data” array. But as of now, nothing changes in the UI. Let’s use the map() method to render the values of the “data” array on the UI. 

{
  data.length ? (
    <ul>
      {" "}
      {data.map((value) => {
        return <li>{value}</li>;
      })}
    </ul>
  ) : null;
}

First, we need to check if there is any value in the “data” array or not. When the array is empty and a value is added, the dynamic list will be created. If a second value is added, it will be inserted in the list and it goes on. 

This is how the code looks. 

import { useState } from "react";

function App() {
  const [data, setData] = useState([]);
  const [input, setInput] = useState("");

  const clickHandler = () => {
    const tempData = data;
    tempData.push(input);
    setData(data);
    setInput("");
    console.log(data);
  };



  return (
    <div className="App">
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />

      <button onClick={clickHandler}>Add</button>

      {data.length ? (
        <ul>
          {data.map((value) => {
            return <li>{value}</li>;
          })}
        </ul>
      ) : null}
    </div>
  );
}


export default App;

 

Output:

React JS Dynamic List Mapping

 

 

Wrapping it up

So the map() method is a commonly used JavaScript array method. As stated in this tutorial, map() is used to create lists in React. It can be used to render an array as a list or to create dynamic lists as we learned in this tutorial. So, the concept of the map() method is simple, yet very powerful.






Post a Comment
Join the community

0 Comments
0
Written By
jatt01990