The map method is a part of ES6 that is especially useful for React developers. What is it and how does it work? Let’s take a look.
You can call array.map() on any array in your code to create a new array which is populated by ‘mapping’ each element in array1 to array2. What actually ends up in array2 is determined by the callback function you passed into the map method as an argument.
I love the below pseudo code that uses emojis to give a high-level visual representation of how map works.
The initial array is mapped over with the ‘cook’ method to achieve the output array – cooked food!
[🐮,🐓,🥔].map(cook) => [🍔,🍗,🍟]
In the simple example below, we are using the map method to create a new array with each element of the original array multiplied by two:
// Our array1 initialisation const array1 = [1,4,9,16]; // array1 mapped over into a new variable called map1 const array2 = array1.map(x => x * 2); // Outcome array2 = [2,8,18,32]
In practical terms, the map method is really useful in React, particularly for looping over an array inside JSX – it keeps your code really neat and saves you from having to call functions that exist outside of your JSX to do this.
Here’s a snippet of that concept in action in a simple React twitter clone I built.
The below is code from the ‘TweetList’ component which renders an individual tweet component for each tweet in the array
Callback functions in map accept the following arguments:
- value – what we’ve seen so far
- index – the array index of the array element you’re currently on
- array – the whole array
You can also pass an object to assign to the ‘this’ keyword after the callback function.
Create your free account to unlock your custom reading experience.