Introduction
In this blog, we will try to understand what is map function and how to use and render list of items in react js application.
What is Map function
In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.
How to use map function
Add a new file in src folder and named it as Mapdemo.js as below.
import React,{Component } from 'react'
function MapDemo(){
const array1 = [1,2,3,4,5];
const map1 = array1.map(item => item*2 + ",")
return(
<h3>{map1}</h3>
)
}
export default MapDemo;
Go to App.js and import this component and use it.
Description of code
Here we have taken a simple array ayyar1 of number and we want to transform an array of multiply by 2 using this array.
So, for applying this transformation, map takes the function which we pass as an argument and that function will get executed for every item in a given array. The result of this function will be stored in newly created array.
Use “npm start” to run the project in localhost.
Summary
In this blog, we learn what is map method and how to use it in react js application.