Author avatar

Gaurav Singhal

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

Gaurav Singhal

  • Jun 5, 2020
  • 5 Min read
  • 198 Views
  • Jun 5, 2020
  • 5 Min read
  • 198 Views
Web Development
Front End Web Development
Client-side Framework
React

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.

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

Take a look at the example below.

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

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

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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>
  );
};
jsx

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.

1
2
3
4
5
const imageSizes = [
  { name: "horizontal", width: 600, height: 380 },
  { name: "vertical", width: 400, height: 650 },
  { name: "thumbnail", width: 300, height: 300 },
];
js

You need to normalize the object to a string with the following format: "Horizontal image - 600 x 380".

1
2
3
4
imageSizes.map((a) => {
  const capitalizedName = a.name[0].toUpperCase() + a.name.slice(1);
  return `${captalizedName} image - ${a.width} x ${a.height}`;
});
js

Next, make this into a reusable utility function and name the function stringifyImageSizes.

1
2
3
4
5
6
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}`;
  });
};
js

Add the export keyword before the function declaration so that you can access it in any other .js or .jsx files.

1
2
3
export const stringifyImageSizes = (imageSizes) => {
  // ...
};
js

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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>
  );
};
jsx

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.

1