Using map method in real word use cases; mostly in React

Using map method in real word use cases; mostly in React

24th January 2019 0 By Azadeh

As we know the map() method creates a new array with the results of calling a provided function on every element in the calling array.

Therefore whenever we need to manipulate data without actually changing the data itself, map is the best option.

Render lists using map

Basically the most use case for map in React specifically is to ender lists of items. Whether it is a list of blog posts or comments or just a simple list of names as below:

const names = ["Denis", "Dan", "Fred", "Jane", "Lena"];
const NamesList = () => (
    <ul>{ => <li key={name}> {name} </li>)}</ul>

We return JSX code using map method to create the list for us. As we know we need to specify the key attribute in our React code to have a unique identity for each list item.

map in react
map method in React

Create an array from Objects

Additionally we can use the map method to manipulate array of objects. In this example we create and array based on an object and add an age for each person in the new array:

 const myUsers = [
    { name: 'Dan', likes: 'chicken' },
    { name: 'Lena', likes: 'meat' },
    { name: 'Fred', likes: 'fish' }

const foodLovers = => {
    const container = {};
    container[] = item.likes;
    container.age = * 10;

    return container;

// [{Dan: "chicken", age: 30}, {Lena: "meat", age: 40}, {Fred: "fish", age: 40}]

Using map like a filter method

Although we have filter and other methods in this use case but sometimes we can use map to filter a specific data from an array or array of objects. Have a look at a simple example which I explain below:

// What you have
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
// What you need
[20, 24, 56, 88]

Using map we can simply write the code:

const officersIds = =>;

Obviously the result is simple and efficient and could be used in loops and lists as expected from map.

Practically map is the number one solution whenever we have some kind of data ready to be used. Either we want to loop through it or just simply take a new array out of it. We will not change the actual data but change the way and how we are going to use it. Therefore it is mostly used when we get iterable data from outside or side effects especially in React.

Thank you for reading.