In react, the map method is used to traverse and display a list of similar objects of the component; the map method is not unique to react and can call standard JavaScript functions on any array. The map method calls the provided function on each element of the calling array. to create an array.
The operating environment of this tutorial: Windows 10 system, react version 17.0.1, Dell G3 computer.
Map is a data collection type in which data is stored in the form of pairs. It contains a unique key to which the values stored in the map must be mapped. We cannot store duplicate pairs in map(), this is because each stored key is unique and it is mainly used for fast searching and finding data.
In React, the map method is used to iterate and display a list of similar objects in a component. map is not specific to React. Instead, it is a standard JavaScript function that can be called on any array. The map() method creates a new array by calling the provided function on each element in the calling array.
example
In the given example, the map() function accepts an array of numbers and doubles its value, we assign the new array returned by map() to the variable doubleValue and record it.
var numbers = [1, 2, 3, 4, 5]; const doubleValue = numbers.map((number)=>{ return (number * 2); }); console.log(doubleValue);In React, the map() method is used for:
1. Traverse the list elements.
example
import React from 'react'; import ReactDOM from 'react-dom'; function NameList(props) { const myLists = props.myLists; const listItems = myLists.map((myList) => <li>{myList}</li > ); return ( <div> <h2>React Map example</h2> <ul>{listItems}</ul> </div> ); } const myLists = ['A', 'B', 'C' , 'D', 'D']; ReactDOM.render( <NameList myLists={myLists} />, document.getElementById('app') ); export default App;2. Traverse the list elements by key.
example
import React from 'react'; import ReactDOM from 'react-dom'; function ListItem(props) { return <li>{props.value}</li>; } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <ListItem key={number.toString()} value={number} /> ); return ( <div> <h2>React Map example</h2> <ul> {listItems} </ul> </div> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('app' ) );