React Map

React Map

The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of a component. The map() method mainly creates a new array simply by calling the provided function on every element within the calling array.

The map() function is the data collection type in which data stores in the form of pairs. The map() function contains a unique key. The value which gets stored in the map() function must be mapped with the key. You cannot store the duplicate pair in the map() function. It happens because every stored key is unique. We mainly used it for the fast searching of data.

Example:

In the following example, there is a map() function, which is taking an array of numbers and half their values. We assign the new array, which is returned by map() function to the variable value and log it.

var numbers = [1, 2, 3, 4, 5]; 
const value = numbers.map((number)=>{ 
return (number / 2); 
}); 
console.log(value);  

In React, the map() function is used for:

Traversing the List element

import React from 'react'; 
class App extends React.Component{
constructor(props){
super(props);
this.state={
users:['Arun','Shivam','Raman','Sagar','Anuj','Akash','Tanuj']
}
}
render(){ 
return(
    {this.state.users.map((user,index)=>(
  • {user}
  • ))}
) } } export default App;

Output:

Traversing the List element

As we can see above code is working fine, but when you inspect (ctrl + shift + I) this output in your browser and open the console section then you will see a warning as shown in the following image:

As we can see above code is working fine

This warning occurs because, in the previous example, we have not defined any key attribute and react asks for a key attribute by which the item gets uniquely identified.

So, if we re-write the above code and assign a key by using the index value, then the warning will be resolved. Now, we are adding the key attribute in the above code.

App.js

import React from 'react'; 
class App extends React.Component{
constructor(props){
super(props);
this.state={
users:['Arun','Shivam','Raman','Sagar','Anuj','Akash','Tanuj']
}
}
render(){
return(
    {this.state.users.map((user,index)=>(
  • {user}
  • //Add the key attribute ))}
) } } export default App;

After executing the above code snippet, we will get the same output, but when we inspect it and open the console section, then we will not get any warning. You can see it in the following image:

open the console section

So, it is always recommended to use the key attribute to get rid of these unnecessary warnings.