Map in React
Published: 2020-10-13 15:07:58

The ***map()*** function is used to iterate over an array and manipulate or change data items. In React, the map() function is most commonly used for rendering a list of data to the DOM.

To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array. From the callback parameters, you can access the current element, the current index, and the array itself. The map() function also takes in an optional second argument, which you can pass to use as this inside the callback. Each time the callback executes, the returned value is then added to a new array.For example:
```react
const num = [3, 8, 11, 7, 5];

const num2x = num.map((n) => n * 2);

console.log(num2x); // [6, 16, 22, 14, 10]
```
***Usage in React***
Consider an array of objects that contains user id and name. To display it to the DOM, you need to use the map() function and return JSX from the callback function. This is the most common use case of the map() function in React.
```react
const Users = () => {
  const data = [
    { id: 1, name: "Timo Werner },
    { id: 2, name: " Wayne Gakuo" },
    { id: 3, name: "Kai havartz" },
  ];

  return (
    <div className="users">
      {data.map((user) => (
        <div className="user">{user}</div>
      ))}
    </div>
  );
};
```
Other than rendering, the map() function can also be used in a utility function, which can be imported from another file.

Suppose you have an array of different image sizes.
```react
const imageSizes = [
  { name: "horizontal", width: 600, height: 380 },
  { name: "vertical", width: 400, height: 650 },
  { name: "thumbnail", width: 300, height: 300 },
];
```
You need to normalize the object to a string with the following format: "Horizontal image - 600 x 380".
```react
imageSizes.map((a) => {
  const capitalizedName = a.name[0].toUpperCase() + a.name.slice(1);
  return `${captalizedName} image - ${a.width} x ${a.height}`;
});
```
Next, make this into a reusable utility function and name the function stringifyImageSizes.
```react
const stringifyImageSizes = (imageSizes) => {
  return imageSizes.map((a) => {
    const capitalizedName = a.name[0].toUpperCase() + a.name.slice(1);
    return `${captalizedName} image - ${a.width} x ${a.height}`;
  });
};
```

Add the export keyword before the function declaration so that you can access it in any other .js or .jsx files.
```react
export const stringifyImageSizes = (imageSizes) => {
  // ...
};
```
Now, import the function using the import keyword in the component file.
```react
import React from "react";

import { stringifyImageSizes } from "./utils";

const Images = () => {
  const imageSizes = [
    { name: "horizontal", width: 600, height: 380 },
    { name: "vertical", width: 400, height: 650 },
    { name: "thumbnail", width: 300, height: 300 },
  ];

  const normalizedImageStrings = stringifyImageSizes(imageSizes);

  return (
    <div className="images">
      {normalizedImageStrings.map((s) => (
        <div className="image-type">{s}</div>
      ))}
    </div>
  );
};
```
And that's it. Pretty easy, right?

Using the map() function, you can pretty much do all sorts of manipulations without mutating the original array. The non-mutation part is essential, as it does not cause any side effects by default and makes it easy to debug your code. If you want to mutate the original array, you can use the traditional for or any other type of loop, or you can use the forEach() function.