What is map() used for in React?
map() is a JavaScript function commonly used in ReactJS. It is used to traverse a list or array and create a new one. The function allows us to visit each array element and perform the required actions.
Why is it used in ReactJS?
The map() function transforms an array of data into an array of React elements that can then be rendered as part of map() function on it. The map() function will traverse each element individually.
Note:
map()functions are also used instead of loops in ReactJS, as loops cannot be implemented insidereturn()in the ReactJS code.
Code
For better understanding, we will take the following code as an example:
import React from 'react';
require('./style.css');
import ReactDOM from 'react-dom';
import App from './app.js';
ReactDOM.render(
<App />,
document.getElementById('root')
);
Code explanation
Line 3–7: An array,
employees, of employees' data.Line 9–23: The
EmployeeList()function is responsible for creating the front-end. It takes theemployeearray as an argument.Line 14: The
map()function is implemented on theemployeesarray. Theemployeeparameter will be used to traverse each element of the array.Line 15–17: The
employeeparameter uses the keys of each array element to render their values.Line 25–31: The
App()function calls theEmployeeList()function.
Free Resources