Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use the Map() Function to Export JavaScript in React

Jun 5, 2020 • 5 Minute Read

Introduction

When working on React apps, you will encounter use cases where you have to deal with arrays. These cases could involve data from an external API, responses from your backend services, or, most commonly, rendering a list of data items in your component.

The map() function lets you manipulate the items in an array by iterating and accessing individual items. In this guide, you will learn how to use the map() function and export it.

The Map() Function

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.

      let new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
    

Take a look at the example below.

      const num = [3, 8, 11, 7, 5];

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

console.log(num2x); // [6, 16, 22, 14, 10]
    

Here, each element from the array num is multiplied by two and stored in a new array. Note that the map() function does not mutate the original array; instead, it creates a new array with the modified elements from the original array.

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.

      const Users = () => {
  const data = [
    { id: 1, name: "John Doe" },
    { id: 2, name: "Victor Wayne" },
    { id: 3, name: "Jane Doe" },
  ];

  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.

      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".

      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.

      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.

      export const stringifyImageSizes = (imageSizes) => {
  // ...
};
    

Now, import the function using the import keyword in the component file.

      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 voila, that was it. Pretty easy, right?

Conclusion

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.

Learn More