How to use map in React components? Complete Guide with Examples

How to use map in React components? Complete Guide with Examples

In this article, we are going to see what is map method. and How to use them in React components with examples. We will also be going to compare before using the map method and after using the map method in our components. So be ready to learn something new from this article. I have published various articles on Codedamn News so you can also visit them to learn something new from them.

If you want to start learning code online or you have started but don’t know where to practice then you can visit Codedamn for amazing courses and practice your coding skills on their playground.

Let’s start with our first topic what is the map method.

What is the map method?

The map method works the same as the for and forEach loops. But there is a difference between the map and the other loop methods.

Using the map method we can perform certain operations on the existing array without even changing the existing array. It will loop over the existing array and creates a new array containing all the results of that callback function which we passed into the map method.

Let’s see an example to understand it more clearly.

const numArray = [1, 2, 3, 4, 5, 6, 7, 8];
const multiPliedArray = numArray.map((num) => num * 10);
console.log(multiPliedArray); //output [ 10, 20, 30, 40, 50, 60, 70, 80 ]
console.log(numArray); // output [1, 2, 3, 4, 5, 6, 7, 8]
Code language: JavaScript (javascript)

As you can see in the above example I have created an array of numbers. and then on the next line, I used the map method to loop over the existing array and passed an anonymous callback function which is returning every array element multiplied by 10. In a new array, it will not modify the existing array. This is what the map method is and now we will be going to see how we can use the map method in React component and how can this map method will make our work easy in React.

Why do we need to use the map method?

Before we know how to use the map in react components we will first see why we need the map method in React components.

Let’s suppose we have JSON data ie an array of objects which contains information about random users. And what we want now is to create a user card component for each of the users which are present in that JSON data.

Now without a map function or method, we will write an App component inside which we will manually add the information about the users which are present in that JSON data. I’m adding the code example below so you can look at it to get an idea.

import "./styles.css";

const users = [
  { name: "amol shelke", age: 18 },
  { name: "Max", age: 22 },
  { name: "Naruto Uzumaki", age: 20 }
];

export default function App() {
  return (
    <div className="App">
      <ul>
        <li>
          {users[0].name} {users[0].name} years old
        </li>
        <li>
          {users[1].name} {users[1].name} years old
        </li>
        <li>
          {users[2].name} {users[2].name} years old
        </li>
      </ul>
    </div>
  );
}

Code language: JavaScript (javascript)

As you can see in the code example, we are rendering three lists for each user which is present in that user’s array. Now This is just an example, but in the big projects, we don’t use this kind of small array of objects. We use APIs to fetch data from a third-party server and we don’t know how much data we will get on that fetch success.

So when we don’t know how much JSON data we have or when we want to render multiple lists item without repeating one element more than once. In that case, we can use the map method.

How to use the map in React components?

Using the map method in react components are the same as we use it on the array. We first create an array of objects which will hold our data for creating elements more than one.

And then we will loop over that array of objects. And on that map method, we will pass an element that will create the same element for all of the objects which are present in that state array.

Let’s see this in practice. We will now be going to convert the example that we saw above by adding the map method to render the user list items.

Example 1

import "./styles.css";

const users = [
  { name: "Amol Shelke", age: 21 },
  { name: "Max", age: 22 },
  { name: "tsukishima", age: 19 }
];

export default function App() {
  return (
    <div className="App">
      <ul>
        {users.map((user) => (
          <li key={Math.random().toString()}>
            {user.name} {user.age}(years old)
          </li>
        ))}
      </ul>
    </div>
  );
}

Code language: JavaScript (javascript)

In this example, we added the map method to our users component. And what that map method is doing is that it is looping all over the user’s array and for each user object it creates a list item.

Which holds the user name and user age. And as the output, we will get three list items for the three user objects which are present in that user’s array. As you can see below in the output image.

Output

Map example output.
map example output.

Example 2

Now even if we add more user objects to the user’s array it will automatically create a list item for them too.

But before without the map method, if we add the new user objects to the user’s array we also have to add another list item for the new user’s object. This is how we can use the map method in our React components. Let’s now add some more user objects to our user’s array and check what will be the output on the UI.

import "./styles.css";

const users = [
  { name: "Amol Shelke", age: 21 },
  { name: "Max", age: 22 },
  { name: "tsukishima", age: 19 }
];

users.push({ name: "Hinata hyuga", age: 28 });
users.push({ name: "Naruto uzumaki", age: 29 });

export default function App() {
  return (
    <div className="App">
      <ul>
        {users.map((user) => (
          <li key={Math.random().toString()}>
            {user.name} {user.age}(years old)
          </li>
        ))}
      </ul>
    </div>
  );
}

Code language: JavaScript (javascript)

Now I pushed 2 new user objects to the user’s array And I don’t even create a list item for them but using the map method will automatically create the 2 new user lists and will add that to the UI. It will make sense after seeing the output which is given below.

Output

As you can see in the output the new list items are added on the UI below the existing list items. The map method is really helpful when working with components and multiple list items. These are some basic examples, but they are enough to get an idea about how to use the map function in React.

adding new objects to the user's array
adding new objects to the user’s array

Conclusion

In this article, we learned about what is the map method, why we need to use the map method in React component, and how to use the map in React component with examples. I hope you learned something from this article. If you are new to programming and don’t know where to start learning then you should visit Codedamn for amazing courses.

Sharing is caring

Did you like what Amol Shelke wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far