Learn React, React

Map() method in ReactJS

In this article, we will learn about the map() method. This article will help you to understand the concept of the map()...

Written by Rohit Sharma · 1 min read >

In this article, we will learn about the map() method. This article will help you to understand the concept of the map() method.

What is React Map?

The standard JavaScript function is a map, which is a kind of data collection. Pairs of data are saved in this place. A distinct key is mapped to each value kept in the map. Because a duplicate pair is not permitted in a map, quick data searching is possible.

Let’s Do Coding!

Example 1: In the return statement, a Static Array of Items

import React from 'react'

const App = () => {
const data = [
  {
    class: "11th",
    age: "17"
  },
  {
    class: "12th",
    age: "18"
  },
  {
    class: "10th",
    age: "17"
  },
  {
    class: "9th",
    age: "18"
  }
];



  return (
       <ul>
      {data.map((students) => (
        <li key={students.id}>{students.class}</li>
      ))}
    </ul>
  )
}

export default App

Output

This will generally be the most common mode of using maps in React projects. Usually, if parts are sorted logically and understandable, I don’t see a problem with placing this code right in the return statement.

Example 2: In a Function, a Static Array of Items

import { useEffect, useState } from 'react'

const App = () => {


  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://gorest.co.in/public/v2/users")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  return (
    <ul>
      {data.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );

}

export default App

Output

As you learn more about React and other frontend frameworks, dealing with APIs is practically a guarantee.

Conclusion

The map() method in ReactJS is most frequently used to render a list of data to the DOM. It is incredibly well-liked because it is simple to use. As we saw in this post, looping over an array of items greatly benefits from the map method. This technique also allows us to change the data in the array.

This article will help you to learn about Map() method. Thank you for reading my article. Hope you understand very well the concept of the map() method.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *